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

mem*_*und 10 java spring spring-mvc

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

dir/config/application.properties

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

@Value("${my.property}")
private String prop;
Run Code Online (Sandbox Code Playgroud)

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

但是怎么样?

Ess*_*Boy 6

使用下面的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));
    }
}
Run Code Online (Sandbox Code Playgroud)

您的主配置看起来像:

@EnableScheduling
@PropertySource("classpath:/config.properties")
public class HelloWorldConfig {
}
Run Code Online (Sandbox Code Playgroud)

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

environment.get("my.property");
Run Code Online (Sandbox Code Playgroud)

  • 这并没有回答有关使 @Value 具有新属性的问题。我希望一定有一种方法可以让原型 bean 重新加载新属性。如果没有的话我会感到震惊。 (2认同)