使用 XML 注释,我使用以下配置注入地图 -
<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 个 bean - DefaultImpl 、 PersonImpl 和 CompanyImpl 。如何使用 Spring 注解将它们注入为地图?
编辑:目前,我已经执行了以下操作,但不确定这是否是推荐的方法
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);
}
1.注入一个包含对象的地图, (使用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.注入包含字符串的映射 (使用属性文件)
您可以将字符串值注入到映射中属性文件使用@Value注释和SpEL像这样。
例如,属性文件中的以下属性。
propertyname={key1:'value1',key2:'value2',....}
在你的代码中,
@Value("#{${propertyname}}")
private Map<String,String> propertyname;
Note:1.主题标签作为注释的一部分。
2.Values must be quotes, else you will get SpelEvaluationException
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)