2016-10-06 113 views
3

的地圖使用XML註釋,我注射使用下面的配置地圖 -Spring註解 - 注射對象

<bean id = "customerfactory" class = "com.brightstar.CustomerFactory"> 
     <property name = "getCustomerMap"> 
      <map key-type = "java.lang.String" value-type = "com.brightstar.CustomerImpl"> 
       <entry key = "DEFAULT" value-ref = "getDefaultImpl"></entry> 
       <entry key = "PERSON" value-ref = "getPersonImpl"></entry> 
       <entry key = "COMPANY" value-ref = "getCompanyImpl"></entry> 
      </map> 
     </property> 
    </bean> 

我已經建立3種豆 - DefaultImpl,PersonImpl的和CompanyImpl。我如何使用Spring Annotation將它們注入地圖?

編輯:現在,我已經執行以下,但不知道是否是推薦的方法

private Map<String, CustomerImpl> getCustomerMap ; 
@Autowired 
private GetDefaultImpl getDefaultImpl; 
@Autowired 
private GetPersonImpl getPersonImpl; 
@Autowired 
private GetCompanyImpl getCompanyImpl; 

private static final String DEFAULT = "DEFAULT"; 
private static final String COM = "PERSON"; 
private static final String SOM = "COMPANY"; 


@PostConstruct 
public void init(){ 
    getCustomerMap = new LinkedHashMap<String,CustomerImpl>(); 
    getCustomerMap.put(DEFAULT, getDefaultImpl); 
    getCustomerMap.put(PERSON, getPersonImpl); 
    getCustomerMap.put(COMPANY, getCompanyImpl);   
} 

回答

4

1.Inject一個地圖包含對象,(使用Java配置

你可以這樣做......

@Configuration 
public class MyConfiguration { 
    @Autowired private WhiteColourHandler whiteColourHandler; 

    @Bean public Map<ColourEnum, ColourHandler> colourHandlers() { 
     Map<ColourEnum, ColourHandler> map = new EnumMap<>(); 
     map.put(WHITE, whiteColourHandler); 
     //put more objects into this map here 
     return map; 
    } 
} 

====================

2.Inject一個地圖包含字符串使用屬性文件

你可以注入字符串值成地圖從性質使用@Value註釋和規劃環境地政司文件喜歡這個。

例如,在屬性文件中的屬性下面。

propertyname={key1:'value1',key2:'value2',....} 

在你的代碼,

@Value("#{${propertyname}}") 
private Map<String,String> propertyname; 

注: 1,#標籤作爲註釋的一部分。

2.Values must be quotes, else you will get SpelEvaluationException 
+0

謝謝。在我的情況下,我必須注入屬性文件中不能出現的對象。 –

+0

謝謝,這有助於。你能評論我的方法嗎?我會接受答案。 –

+0

我不確定,@Postconstruct是初始化bean或管理bean的生命週期的最佳實踐,因爲它是JEE標準,但不是用於注入依賴項。但是,最佳實踐不是規則。 –

1

只需加我2美分。據我所知,你正在實現工廠模式,在運行時切換實現。所以,它是代碼而不是配置,是代碼本身的理想地方,而不是屬性文件。我會採用Sundararaj Govindasamy建議的第一種方法。我在@postConstruct方法中也沒有看到任何問題。但我會與前者一起作爲清潔工。

+0

非常感謝您的意見! –