SpringBoot定制化PropertySource

步骤如下:

在这里插入图片描述
使用CustomEnvironmentPostProcessor实现EnvironmentPostProcessor(Spring框架中的EnvironmentPostProcessor接口允许在Spring应用程序的环境被完全配置之前对其进行自定义处理。)

@Slf4j
public class CustomEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        Resource resource = new ClassPathResource("custom.properties");
        try {
            PropertySource ps = loader.load("xxx", resource)
                    .get(0);
            propertySources.addFirst(ps);
        } catch (Exception e) {
            log.error("Exception!", e);
        }
    }
}

然后在resource目录下创建一个custom.properties的配置文件,定义如下:

custom.greeting=hello

简单做一个测试:

@SpringBootApplication
@Slf4j
public class PropertySourceDemoApplication implements ApplicationRunner {
	@Value("${custom.greeting}")
	private String greeting;

	public static void main(String[] args) {
		SpringApplication.run(PropertySourceDemoApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		log.info("{}", greeting);
	}
}

输出结果如下:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值