Camel处理器未自动连接Spring bean



不确定为什么这不起作用-我已经在camel路由(HelloCamelClient)之外测试了CustomerService自动布线,它工作得很好,但一旦我把它放在camel Processor类中,它就不能正确地自动布线。它在process()函数中达到cs.getCustomer(),然后抛出一个NullPointerException。

Camel上下文XML

    <camelContext trace="false" xmlns="http://camel.apache.org/schema/spring">
    <route id="HelloWorldRoute">
        <from uri="jetty:http://0.0.0.0:8888/hellocamel"/>
        <transform>
            <language language="simple">Hello ${body}</language>
        </transform>
    </route>
    <route id="HelloWorldRoute2">
        <from uri="jetty:http://0.0.0.0:8888/hellocamel2"/>
        <to uri="bean:myProcessor"/>
    </route>
</camelContext> 
<bean id="myProcessor" class="com.fusesource.byexample.hellocamel.impl.CamelHandler"/>
<bean id="customerService" class="com.fusesource.byexample.hellocamel.impl.CustomerService2" />
<bean id="HelloCamelClient" class="com.fusesource.byexample.hellocamel.impl.HelloCamelClient" />

CamelHandler.java

package com.fusesource.byexample.hellocamel.impl;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fusesource.byexample.hellocamel.impl.CustomerService2;
@Service
public class CamelHandler implements Processor {
    @Autowired 
    private CustomerService2 cs;
    public CamelHandler() {
        // 
    }
    public void test() throws SQLException {
    }
    @Override
    public void process(Exchange arg0) throws Exception {
        cs.getCustomer();
        arg0.getOut().setBody(cs.getCustomer());
    }

}

我更改了代码,为DataSource和CustomerService设置了setter方法,现在它似乎工作得很好。但不知道为什么。

2018年,不再是NOOB更新:这是因为提供了一个空构造函数,Spring只能使用它来构建bean,并且不可能设置任何@Autowired字段。添加setter使Spring能够填充这些字段。(首选)替代方案是使用构造函数注入,而不是@Autowired注释。

最新更新