我正在试验Spring的重载执行器,它的想法是能够对application.yaml文件的变化做出反应并进行调整。
在我的代码中,我使用的是AppConfigurationProperties类,它绑定到前缀app并保存配置属性。对其中一些属性的更改需要在代码中进行一些操作。
这就是为什么我认为我可以点击一个ApplicationListener<EnvironmentChangeEvent>事件,它是在重新加载事件之后触发的。不幸的是,这个事件对我来说是无用的,因为我似乎不知道如何将新来的PropertySources映射到我的AppConfigurationProperty类。
试图从event context获取bean也失败了,因为它提供了相同的实例:
ApplicationContext context = (ApplicationContext) event.getSource();
MyConfigurationProperties newProps = context.getBean(MyConfigurationProperties.class);我想我在这里做错了什么,或者我错过了什么。
这是我的密码:
@SpringBootApplication()
@EnableWebFlux
@EnableConfigurationProperties({AppConfigurationProperties.class})
@Slf4j
public class MyApplication
{
public static void main(String[] args)
{
SpringApplication.run(MyApplication.class, args);
}
}
@ConfigurationProperties(prefix = "app")
@Order(Ordered.HIGHEST_PRECEDENCE)
@ToString
public class AppConfigurationProperties
{
@Getter
private final List<String> users;
}
@Service
@Slf4j
public class UserService
{
private final AppConfigurationProperties properties;
@Autowired(required = true)
public SymbolPairRecorderService(AppConfigurationProperties properties)
{
// The purpose of this service is to subscribe/unsubscribe form some
// websockets based on the `app.users` list. Changes to the list
// should result in a `new websocket subscription` (for added users)
// or `disposal of existing subscription` (for removed users)
this.properties = properties;
}
public SymbolPairRecorderService()
{
this(new AppConfigurationProperties());
}
@Bean
protected ApplicationListener<EnvironmentChangeEvent> onEnvironmentChange()
{
return event -> {
ApplicationContext context = (ApplicationContext) event.getSource();
// Okay, now what? How to get the new `AppConfigurationProperties` instance
// so I could then make my own `diff` and proceed?
}
}
}发布于 2022-11-26 22:55:54
您可以使用此配置来表示环境中的更改:
@Configuration
public class AppConfiguration {
@EventListener({EnvironmentChangeEvent.class, ContextRefreshedEvent.class})
public void onRefresh() {
// add your implementation
}
}https://stackoverflow.com/questions/74583586
复制相似问题