2011-12-01 137 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/>