如何从Spring中的application.properties重新加载@Value属性?

时间:2016-10-27 14:50:33

标签: java spring spring-mvc

我有一个spring-boot申请。在run文件夹下,还有一个额外的配置文件:

dir/config/application.properties

当应用程序启动时,它使用文件中的值并将它们注入:

@Value("${my.property}")
private String prop;

问题:如何触发重新加载@Value个属性? 我希望能够在运行时更改application.properties配置,并更新@Value字段(可能通过调用应用程序内的/reload servlet来触发更新。

但是怎么样?

1 个答案:

答案 0 :(得分:5)

使用以下bean每1秒重新加载config.properties。

@Component
public class PropertyLoader {

    @Autowired
    private StandardEnvironment environment;

    @Scheduled(fixedRate=1000)
    public void reload() throws IOException {
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> resourcePropertySource = propertySources.get("class path resource [config.properties]");
        Properties properties = new Properties();
        InputStream inputStream = getClass().getResourceAsStream("/config.properties");
        properties.load(inputStream);
        inputStream.close();
        propertySources.replace("class path resource [config.properties]", new PropertiesPropertySource("class path resource [config.properties]", properties));
    }
}

您的主配置看起来像:

@EnableScheduling
@PropertySource("classpath:/config.properties")
public class HelloWorldConfig {
}

而不是使用@Value,每次你想要最新的属性时你都会使用

environment.get("my.property");