@PropertySource 使用

@PropertySource 可以加载指定的属性文件(*.properties)到 Spring 的 Environment 中。可以配合 @Value 和
@ConfigurationProperties 使用。

使用方法


@Data
public class TestProperty {
	private String name;
	private Boolean male;
	private Integer age;
	private List<String> alias;
	private Map<String, Integer> score;
}



@Configuration
@PropertySource({"classpath:/config/box.properties"})
public class BoxPropertyConfig {

	@Bean
	@ConfigurationProperties("box")
	@ConditionalOnProperty(prefix = "box.test", name = {"enabled"})
	@ConditionalOnMissingBean
	public TestProperty testProperty() {
		return new TestProperty();
	}
}

// src/main/resource/config/box.properties
box.name=yuan
box.male=true
box.age=20
box.alias=a,b,c

box.score.Chinese=80
box.score.math=100
box.score.English=90

// src/main/resource/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.demo.box.basic.config.BoxPropertyConfig

  • 可以实现 TestProperty Bean的属性注入。
  • 同时可以在 application.yml 或者 application-dev.yml 定义同名属性进行 值的覆盖。
  • 通过注解@PropertySource导入进来的属性源的优先级是最低的。

动态更新

若系统接入Apollo,使用Apollo进行动态更新属性值,不生效,原因在于 @ConfigurationProperties 目前不支持属性值的热更新。

法一:

可以考虑使用 @Value 进行属性注入,能够实现 动态更新属性值。

法二:

创建 ApolloConfigChangeListener ,发布环境变量变更Event。
@Component
public class ApolloConfig implements ApplicationContextAware {


    private ApplicationContext applicationContext;

	@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @ApolloConfigChangeListener
    private void someOnChange(ConfigChangeEvent changeEvent) {
        Set<String> changedKeys = changeEvent.changedKeys();
        changedKeys.forEach(k -> {
            ConfigChange change = changeEvent.getChange(k);
            log.info(change.toString());
        });
        // 更新@ConfigurationProperties注解的bean
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));
    }
}

参考

  • https://blog.csdn.net/lkg5211314/article/details/123938380
  • https://blog.csdn.net/TomCosin/article/details/123821092
  • https://developer.aliyun.com/article/911386
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值