【问题标题】:How can I get the bean of a property file in Spring-Boot?如何在 Spring-Boot 中获取属性文件的 bean?
【发布时间】:2017-08-14 22:39:44
【问题描述】:

我需要玩弄属性文件的键。键是动态的,所以我需要下面提到的属性文件的 bean 作为我当前正在运行的 Spring 应用程序。

弹簧配置:

<bean id="multipleWriterLocations" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="ignoreResourceNotFound" value="true" />
        <property name="locations">
            <list>
                <value>classpath:writerLocations.properties</value>
                <value>file:config/writerLocations.properties</value>
            </list>
        </property>
    </bean>

Java 代码:

Properties prop = appContext.getBean("multipleWriterLocations")

我在 Spring-boot 中需要相同的 Properties bean 实例。我需要在不改变功能的情况下将现有的 Spring 应用程序转换为 Spring-Boot。

使用@PropertySource() 获取属性文件值的一种方法,但在这种情况下,我需要键名。但在我的情况下,密钥名称是未知的,我需要从 Properties bean 中获取 keySet。

【问题讨论】:

    标签: java spring spring-boot properties-file


    【解决方案1】:

    您可以使用@ImportResource("classpath:config.xml"),其中config.xml 包含您上面的PropertiesFactoryBean,然后将其自动连接到您的@SpringBootApplication@Configuration 类中。

    @SpringBootApplication
    @ImportResource("classpath:config.xml")
    public class App {
        public App(PropertiesFactoryBean multipleWriterLocations) throws IOException {
            // Access the Properties populated from writerLocations.properties
            Properties properties = multipleWriterLocations.getObject();
            System.out.println(properties);
        }
    
        public static void main(String[] args) {
            SpringApplication.run(App.class, args);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-28
      • 2016-04-29
      • 1970-01-01
      • 2019-01-11
      • 1970-01-01
      • 2018-06-18
      • 2019-02-24
      • 1970-01-01
      相关资源
      最近更新 更多