Spring 3.0 的一些奇怪行为在这里。
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时,它说:
无法实例化 bean 类 [com.service.schedule.TesteAutowired]:未找到默认构造函数;嵌套异常是 java.lang.NoSuchMethodException: com.service.schedule.TesteAutowired。
问题是:为什么,如果 Spring 找到“outroJob”bean,它不会在 TesteAutowired 构造函数上自动装配它?
它必须做什么似乎很明显......