使用 XML 注释,我正在使用以下配置注入(inject) map -
<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 Annotation 将它们作为 map 注入(inject)?
编辑:目前,我已经执行了以下操作但不确定这是否是推荐的方法
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.注入(inject)一个包含对象的Map,(使用Java Config)
你可以这样做......
@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)一个包含字符串的Map(使用属性文件)
您可以像这样使用@Value 注释和SpEL 将字符串值从属性文件 注入(inject)到Map 中。
例如,属性文件中的 below 属性。
propertyname={key1:'value1',key2:'value2',....}
在你的代码中,
@Value("#{${propertyname}}")
private Map<String,String> propertyname;
注意: 1.主题标签作为注释的一部分。
2.Values must be quotes, else you will get SpelEvaluationException
关于java - Spring Annotations - 注入(inject)对象映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39906383/