Spring @Autowired构造函数没有找到默认的构造函数

chu*_*edw 5 java spring default-constructor autowired

这里是Spring 3.0的一些奇怪行为。

package com.service.schedule;

import org.springframework.stereotype.Component;

@Component("outroJob")
public class OutroJob {

    public void printMe() {
        System.out.println("running...");
    }

}
Run Code Online (Sandbox Code Playgroud)

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

这些bean均未在applicationContext.xml上声明

因此,行outroJob.printMe(); 工作正常...打印“正在运行...”

但是,当我尝试获取“ testeAutowired” bean时,它说:

无法实例化Bean类[com.service.schedule.TesteAutowired]:找不到默认的构造函数;默认值为0。嵌套异常是java.lang.NoSuchMethodException:com.service.schedule.TesteAutowired。

问题是:为什么,如果Spring找到了“ outroJob” bean,那么它不会在TesteAutowired构造函数上对其进行自动装配?

似乎很明显它必须做什么...

sou*_*eck 1

尝试使用 ApplicationContext 而不是 XmlBeanFactory。XmlBeanFactory 不后处理注释,即不使用 AutowiredAnnotationBeanPostProcessor 来解释您所遇到的行为。

这是更多解释