2011-12-01 143 views
4

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构造函数中自动装配它?

它似乎很明显它有什么做的......

+0

会发生什么事,如果你使用的ApplicationContext代替XmlBeanFactory的?我发现3.1中已经弃用了XmlBeanFactory,也许这就是其中一个原因。 – soulcheck

回答

0

尝试使用

@Autowired(required=true) 
public TesteAutowired(OutroJob outroJob) { 
    outroJob.printMe(); 
} 

这应该强制Spring使用该构造函数。否则,它建立一个构造函数列表并挑选出最佳候选。显然,它真的想要一个默认的构造函数作为候选人,我猜。

参考:使用的ApplicationContext代替XmlBeanFactory的http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.html

+3

当'required'的默认值为'true'时,我无法想象这会如何帮助。即'@ Autowired' =='@Autowired(required = true)' –

0

为该组件创建一个inteface,并尝试自动装配接口和诺尔类与自动装配Autowired构造器。

0

我得到相同的错误信息,但有不同的问题。我正在使用XML配置并在类构造函数中放入@Autowired

我解决了这个问题,通过启用注释驱动的配置在我的XML配置文件:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 


    <context:annotation-config/> 
相关问题