栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

@PropertySource 使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

@PropertySource 使用

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

使用方法
@Data
public class TestProperty {
	private String name;
	private Boolean male;
	private Integer age;
	private List alias;
	private Map 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 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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1035293.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号