Not really sure why this isn't working - I've tested the CustomerService
autowiring outside of the camel route (HelloCamelClient
) and it works fine, but once I put it in a camel Processor class, it does not autowire correctly. It gets as far as cs.getCustomer()
in the process()
function, then throws a 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());
}
}
I changed my code to have setter methods for DataSource and CustomerService, and it seems to work fine now. Not sure why though.
2018 AND NOT A NOOB ANYMORE UPDATE: This is because with an empty constructor provided, Spring only has the ability to use that to build the bean, and can't possibly set any @Autowired fields. Adding setters gave Spring the ability to populate those fields. The (preferred) alternative is to use Constructor Injection instead of the @Autowired annotation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With