如何在 Spring-Boot 中获取 属性 文件的 bean?

How can I get the bean of a property file in Spring-Boot?

我需要玩转 属性 文件的密钥。密钥将是动态的,因此我需要下面提到的 属性 文件的 bean 作为我当前的 运行 Spring 应用程序。

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。

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

@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);
    }
}