本文介绍了弹簧注释-注入对象图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用XML批注,我正在使用以下配置注入地图-

Using XML annotation , I am injecting a map using the below config -

   <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将它们作为地图注入?

I have created 3 beans - DefaultImpl , PersonImpl and CompanyImpl. How can I inject these as a map using Spring Annotation?

目前,我已经执行了以下操作,但不确定是否建议这样做

For now , I have performed the below but not sure if it is the recommended approach

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.插入一个包含对象的 Map ,(使用Java Config )

1.Inject a Map which contains Objects, (Using 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.插入一个包含字符串的映射(使用属性文件)

2.Inject a Map which contains Strings (Using properties file)

您可以使用 @Value 批注和 SpEL 属性文件将字符串值注入到Map中.

You can inject String values into a Map from the properties file using the @Value annotation and SpEL like this.

例如,在属性文件中的属性下方.

For example, below property in the properties file.

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

在您的代码中,

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

注意:1.#标签作为注释的一部分.

Note: 1.The hashtag as part of the annotation.

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

这篇关于弹簧注释-注入对象图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:45