2016-10-11 98 views
0

我使用Spring 1.3啓動注入,和我有下面的配置類:@Bean不按名稱獲取

@Configuration 

public class MainConfig { 

    @Bean(name="dateAndTimeFormater") 
    public SimpleDateFormat dateAndTimeFormater(){ 
     return new SimpleDateFormat("yyyy-MM-dd"+Constants.STRING_SEPARATOR+"hh:mm"); 
    } 
    @Bean(name="dateFormater") 
    public SimpleDateFormat dateFormaterBean(){ 
     return new SimpleDateFormat("yyyy-MM-dd"+Constants.STRING_SEPARATOR+"hh:mm"); 
    } 
} 

當我嘗試注入以下豆的名字之一,它拋出: 沒有定義類型爲[java.text.SimpleDateFormat]的合格bean:期望的單個匹配bean,但找到2:dateAndTimeFormater,dateFormater。

這裏是我注入bean的地方: private static SimpleDateFormat sdf;

@Autowired 
@Qualifier("dateAndTimeFormater") 
public static void setSdf(SimpleDateFormat sdf) { 
    myClass.sdf = sdf; 
} 

我試過@Ressource,@Inject。它沒有工作。

任何建議將不勝感激?

+0

我運行你的代碼,這幾乎確定。如果你想自動裝載參數sdf,那麼它不能是'靜態'。然而,你得到的錯誤是,如果你沒有'@Qualifier',所以我認爲你的項目中有一個完全不同的代碼 – reos

回答

0

這是因爲你正試圖連線,靜態方法,Spring容器將不依賴線看靜態引用或方法,why can't you do that

@Autowired 
@Qualifier("dateAndTimeFormater") 
public void setSdf(SimpleDateFormat sdf) { 
    myClass.sdf = sdf; 
} 
+0

我沒有使用靜態方法,它沒有工作。我想在注入Bean的時候,註釋限定符不起作用。當我嘗試了一個簡單的註釋組件類它工作正常??! –