java 如何在Sping Boot 中获取EnvironmentChangeEvent内部的ConfigurationProperty示例?

wgeznvg7  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(103)

我正在试验Sping Boot 的reload actuator,其想法是能够对application.yaml文件的更改做出React并进行适应。
在我的代码中,我使用的是AppConfigurationProperties类,它绑定到前缀app并保存配置属性。对其中一些属性的更改需要在代码中执行一些操作。
这就是为什么我认为我可以进入一个ApplicationListener<EnvironmentChangeEvent>事件,它在reload事件之后被触发。不幸的是,这个事件对我来说非常无用,因为我似乎不知道如何将新出现的PropertySourcesMap到我的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?
        }
    }

}
nfeuvbwi

nfeuvbwi1#

您可以使用此配置来表示环境中的更改:

@Configuration
public class AppConfiguration {

    @EventListener({EnvironmentChangeEvent.class, ContextRefreshedEvent.class})
    public void onRefresh() {
        // add your implementation
    }

}

相关问题