首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Spring中获取ConfigurationProperty实例?

如何在Spring中获取ConfigurationProperty实例?
EN

Stack Overflow用户
提问于 2022-11-26 15:52:24
回答 1查看 31关注 0票数 1

我正在试验Spring的重载执行器,它的想法是能够对application.yaml文件的变化做出反应并进行调整。

在我的代码中,我使用的是AppConfigurationProperties类,它绑定到前缀app并保存配置属性。对其中一些属性的更改需要在代码中进行一些操作。

这就是为什么我认为我可以点击一个ApplicationListener<EnvironmentChangeEvent>事件,它是在重新加载事件之后触发的。不幸的是,这个事件对我来说是无用的,因为我似乎不知道如何将新来的PropertySources映射到我的AppConfigurationProperty类。

试图从event context获取bean也失败了,因为它提供了相同的实例:

代码语言:javascript
复制
ApplicationContext context = (ApplicationContext) event.getSource();
MyConfigurationProperties newProps = context.getBean(MyConfigurationProperties.class);

我想我在这里做错了什么,或者我错过了什么。

这是我的密码:

代码语言:javascript
复制
@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?
        }
    }

}
EN

回答 1

Stack Overflow用户

发布于 2022-11-26 22:55:54

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

代码语言:javascript
复制
@Configuration
public class AppConfiguration {

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

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74583586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档