Spring 3.0在这里出现了一些奇怪的行为。Spring @Autowired构造函数给出没有找到默认构造函数
package com.service.schedule;
import org.springframework.stereotype.Component;
@Component("outroJob")
public class OutroJob {
public void printMe() {
System.out.println("running...");
}
}
和
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");
}
}
这些bean都不是在applicationContext.xml中声明
因此,线outroJob.printMe();正常工作......版画“运行......”
但是,当我试图让“testeAutowired”豆,它说:
无法实例化bean类 [com.service.schedule。 TesteAutowired]:找不到默认构造函数; 嵌套异常是java.lang.NoSuchMethodException: com.service.schedule.TesteAutowired。
问题是:为什么如果Spring发现“outroJob”bean,它不会在TesteAutowired构造函数中自动装配它?
它似乎很明显它有什么做的......
会发生什么事,如果你使用的ApplicationContext代替XmlBeanFactory的?我发现3.1中已经弃用了XmlBeanFactory,也许这就是其中一个原因。 – soulcheck