【问题标题】:Loading a Map in field of Class Object, before the Class instance is returned by getBean method of Spring?在Spring的getBean方法返回Class实例之前,在Class Object的字段中加载一个Map?
【发布时间】:2014-04-17 13:54:00
【问题描述】:

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

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

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

【问题讨论】:

    标签: java spring


    【解决方案1】:

    您可以在 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>
    

    【讨论】:

      【解决方案2】:

      您可以使用 ${...} 在 XML spring 配置文件中使用上下文属性占位符,也可以使用 @value 从 java 类配置文件中使用上下文属性占位符。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-12-06
        • 2016-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 2016-04-02
        • 2012-09-29
        相关资源
        最近更新 更多