在Spring的getBean方法返回Class实例之前,在Class Object的字段中加载Map?

时间:2014-04-17 13:54:00

标签: java spring

我有一个.properties文件有10个键值对,例如age = 10,name = Jon等。我在spring中配置了一个bean,它有一个map作为成员变量。

当我通过Spring加载bean时,我调用了getBean方法,之前应该使用文件中的属性加载Map。怎么做?

我知道这应该在一个生命周期方法中完成,例如使用InitializingBean或init-method配置的afterPropertiesSet。还有其他更好的方法吗?

2 个答案:

答案 0 :(得分:0)

您可以在bean中启用注释:

<context:annotation-config />

然后,您可以使用@PostConstruct注释定义方法。 Spring将在bean初始化过程中执行它:

class MyBean {
    private Map<String, String> properties;

    @PostConstruct
    public void initialize() {
        // read properties and initialize map
    }
}

另一种选择是将Properties直接注入您的bean并提供类似地图的API来访问它们:

<util:properties id="myProperties" location="classpath:my-props.properties">
<bean id="myBean" class="com.example.MyBean">
    <property name="properties" ref="myProperties" />
</bean>

答案 1 :(得分:0)

您可以使用$ {...}在XML spring配置文件中使用context property-placeholder,或者使用@value从java类配置文件中使用context属性占位符。