java - Spring Annotations - 注入(inject)对象映射

标签 java spring

使用 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/

相关文章:

java - 在联结表中使用复合主键时,Hibernate 未正确映射对象 ("Bad value for type"异常)

java - 如何避免在高可用性集群 JBoss EAP 中运行重复任务

java - @RequestBody 对象不会自动反序列化

java - 刷新 fragment 内的 View

java - Java 中的错误逻辑

java - 如何使用 Pageable 对嵌入实体的属性进行排序?

java - Spring框架的Mysql连接错误(org.springframework.jdbc.CannotGetJdbcConnectionException : Could not get JDBC Connection; )

java - 静态嵌套类何时被垃圾回收?

java - 我应该做哪些注释和配置来解析 JSON 对象

java - 无法将通用项实例化为列表 Java