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来触发更新).
但是怎么样?
使用下面的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)
归档时间: |
|
查看次数: |
8486 次 |
最近记录: |