2016-12-01 106 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