PostConstruct注解的方法多次被调用

PostConstruct注解的方法多次被调用

现象

某某公司希望在nacos中可以动态配置黑白名单,例如域名白名单,对在白名单的允许从本站跳转,不在白名单的不允许从本站跳转。
WhiteListConfig类@PostConstruct标记的init方法就是希望只在项目启动时执行,后续不执行。以后改动配置被触发的是onEventChange方法,从而近实时的加载白名单。
But,事与愿违。
在每次修改nacos配置后,onEventChange方法被调用,init方法同样会被调用。

代码示例如下:

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = WhiteListConfig.PREFIX)
public class WhiteListConfig {
   
    public static final String PREFIX = "abc.link";

    private List<String> whiteList;

    @Autowired
    private NacosConfigProperties nacosConfigProperties;

    @PostConstruct
    private void init() {
   
        log.info("---->>>init white list, {}", this);
        refreshWhiteList();
    }

    @EventListener(value = {
   EnvironmentChangeEvent.class})
    public void onEventChange(EnvironmentChangeEvent event) {
   
        Set<String> keys = CollectionUtil.emptyIfNull(event.getKeys());
        boolean inKeySet = keys.stream().anyMatch(ele -> StrUtil.startWith(ele, PREFIX + ".white-list"));
        if (!inKeySet) {
   
            return;
        }
        refreshWhiteList();
    }

    private void refreshWhiteList() {
   
        Map<String, String> properties = EnvironmentUtils.getSubProperties(nacosConfigProperties.getEnvironment(), PREFIX + ".white-list");
        List<String> newWhiteList = MapUtil.emptyIfNull(properties).entrySet().stream()
                .filter(ele -> StrUtil.isNotBlank(ele.getValue()))
                .sorted(Map.Entry.comparingByKey())
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());
        ResponseUtil.r
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值