Camel处理器没有自动装配Spring bean

时间:2014-10-12 23:23:29

标签: java spring apache-camel autowired

不确定为什么这不起作用 - 我已经在驼峰路线(CustomerService)之外测试了HelloCamelClient自动装配并且它工作正常,但是一旦我把它放入骆驼处理器类,它没有正确自动装配。它在cs.getCustomer()函数中达到process(),然后抛出NullPointerException。

Camel Context 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());
    }


}

1 个答案:

答案 0 :(得分:1)

我将我的代码更改为具有DataSource和CustomerService的setter方法,现在它似乎工作正常。不知道为什么会这样。

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