Java – spring @ Autowired constructor given no default constructor found
•
Java
Here are some strange behaviors from spring 3.0
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 in ApplicationContext Declaration on XML
So, line outrojob printMe(); Working properly... Print "running..."
But when I tried to get the "testautowired" bean, it said:
The question is: why doesn't spring automatically start the "outrojob" bean on the testeautowired constructor if it finds it?
It obviously needs to do something
Solution
Try using ApplicationContext instead of xmlbeanfactory Xmlbeanfactory does not post - process annotations, that is, it does not use autowiredannotationbeanpostprocessor to explain the behavior you encounter
Here’s some more explanation
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码