Camel ProducerTemplate没有注入注释配置

时间:2015-05-15 09:13:17

标签: java spring apache-camel activemq

首先,我知道有非常相似的问题(Camel producerTemplate is not injected in spring MVCInitializing camel from Spring annotation config),但它们对我的情况没有帮助。

我有一个使用ProducerTemplate发送消息的bean:

public class SimpleProducer {

   @Produce(uri = "activemq:queue:simple")
   private ProducerTemplate activeMqProducer;

   public void send(String message) {
      activeMqProducer.sendBody(message);
   }
}

当我使用如下所示的注释驱动配置时,它会从send方法中删除NPE(不注入activeMqProducer):

@Configuration
public class AnnotationConfigApp {
   public static void main(String[] args) {
      ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationConfigApp.class);
      SimpleProducer simpleProducer = context.getBean(SimpleProducer.class);
      simpleProducer.send("Hello World!");
   }

   @Autowired
   private ApplicationContext ctx;

   @Bean
   public SimpleProducer simpleProducer() {
      return new SimpleProducer();
   }

   @Bean
   public CamelContext camelContext() throws Exception {
      CamelContext camelContext = new SpringCamelContext(ctx);
      camelContext.start();
      return camelContext;
   }
}

在使用等效(至少我相信)XML配置时,它成功地向ActiveMQ发送消息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:spring="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
       <bean id="simpleProducer" class="makasprzak.so.camel.producer.testing.SimpleProducer"/>
       <spring:camelContext xmlns="http://camel.apache.org/schema/spring" id="simple.sender" />
</beans>

初始化如下:

public class XmlConfigApp {
   public static void main(String[] args) {
      ApplicationContext context = new GenericXmlApplicationContext("context.xml");
      SimpleProducer simpleProducer = context.getBean(SimpleProducer.class);
      simpleProducer.send("Hello World!");
   }
}

我一直在玩CamelContext实现,试过DefaultCamelContext或者一些SpringCamelContextFactory - 没有运气。

问题代码可在GitHub

中找到
<properties>
    <camel.version>2.15.2</camel.version>
    <activemq.version>5.10.0</activemq.version>
    <java.version>1.8</java.version>
</properties>

我在注释配置中错过了什么?

1 个答案:

答案 0 :(得分:2)

您应该在AnnotationConfigApp类中扩展org.apache.camel.spring.javaconfig.CamelConfiguration