2016-12-01 105 views
3

如何配置使用Java DSL和Main對象的屬性文件?駱駝讀取屬性文件

根據this page我應該能夠調用是這樣的:

main.setPropertyPlaceholderLocations("example.properties"); 

然而,根本不起作用。似乎這個選項直到駱駝2.18才被添加,而我正在運行2.17.1。

當讓應用程序以獨立形式運行時,設置屬性文件的原始方式是什麼?

一些背景故事:

我想轉換從春到Java DSL。在轉換過程中,我試圖讓我的駱駝應用程序自行運行。我知道這是使用main.run();實現的。

當我使用CamelContext的時候,我的東西「運行」了,但是它不能自行運行。所以我知道用下面將在這種情況下工作:

PropertiesComponent pc = new PropertiesComponent(); 
pc.setLocation("classpath:/myProperties.properties"); 
context.addComponent("properties", pc); 

有沒有一些方法,我可以告訴main使用該設置嗎?還是還有其他需要的東西?

回答

1

您可以使用下面的代碼片段:

PropertiesComponent pc = new PropertiesComponent(); 
pc.setLocation("classpath:/myProperties.properties"); 
main.getCamelContexts().get(0).addComponent("properties", pc); 

此外,如果你正在使用camel-spring,你可以使用org.apache.camel.spring.Main類,它應該從你的應用程序上下文中使用屬性佔位符。

+1

啊短,甜美的地步。謝謝!你會認爲它會比這更簡潔。但我想這就是爲什麼他們在駱駝2.18中引入新方法! – Jsmith

+0

如果你正在轉向Java配置,你還應該給Spring Boot一個嘗試 - [駱駝對它有很好的支持](https://camel.apache.org/spring-boot.html),刪除了很多樣板。 –

1

由於您提到您正在從Spring XML遷移到Java Config,因此這裏有一個使用屬性並將其注入到Camel路由中的最小應用(它實際上是Spring中的屬性管理,注入到我們的Camel路由bean中) :

my.properties

something=hey! 

Main類

包CA melspringjavaconfig;

import org.apache.camel.spring.javaconfig.CamelConfiguration; 
import org.apache.camel.spring.javaconfig.Main; 
import org.springframework.context.annotation.ComponentScan; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.PropertySource; 

@Configuration 
@ComponentScan("camelspringjavaconfig") 
@PropertySource("classpath:my.properties") 
public class MyApplication extends CamelConfiguration { 

    public static void main(String... args) throws Exception { 
     Main main = new Main(); 
     main.setConfigClass(MyApplication.class); // <-- passing to the Camel Main the class serving as our @Configuration context 
     main.run(); // <-- never teminates 
    } 
} 

MyRoute類

package camelspringjavaconfig; 

import org.apache.camel.builder.RouteBuilder; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.core.env.Environment; 
import org.springframework.stereotype.Component; 

@Component 
public class MyRoute extends RouteBuilder { 

    @Autowired 
    Environment env; //<-- we are wiring the Spring Env 

    @Override 
    public void configure() throws Exception { 

     System.out.println(env.getProperty("something")); //<-- so that we can extract our property 

     from("file://target/inbox") 
       .to("file://target/outbox"); 
    } 
} 
+0

這很整潔,沒有意識到你可以使用註釋配置事物!我希望駱駝頁面有一點清潔流程,這樣我就可以找到一些這些東西了 – Jsmith