Some strange behavior from Spring 3.0 here.
package com.service.schedule;
import org.springframework.stereotype.Component;
@Component("outroJob")
public class OutroJob {
public void printMe() {
System.out.println("running...");
}
}
and
package com.service.schedule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
@Component("testeAutowired")
public class TesteAutowired {
@Autowired
public TesteAutowired(OutroJob outroJob) {
outroJob.printMe();
}
public static void main(String[] args) {
ClassPathResource res = new ClassPathResource("applicationContext.xml");
XmlBeanFactory ctx = new XmlBeanFactory(res);
OutroJob outroJob = (OutroJob) ctx.getBean("outroJob");
outroJob.printMe(); // gives: running...
ctx.getBean("testeAutowired");
}
}
None of these beans are declared on applicationContext.xml
So, line outroJob.printMe(); works fine... prints "running..."
But when I try to get the "testeAutowired" bean, it says:
Could not instantiate bean class [com.service.schedule.TesteAutowired]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.service.schedule.TesteAutowired.
The question is: why, if Spring found the "outroJob" bean it doesn't autowired it on the TesteAutowired constructor ?
It seems obvious what it has to do...
Try using ApplicationContext instead of XmlBeanFactory. XmlBeanFactory doesn't postprocess annotations ie doesn't use AutowiredAnnotationBeanPostProcessor which would explain the behaviour you're experiencing.
Here's some more explanation
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