代码方式获取springboot的application.properties属性值并映射到具体的PropertiesSource指定类

有没有想过,不用@Value注解获取springboot的application.properties文件
而且,还是在environment对象还是没有完全初始化的情况下获取,下面就介绍下具体的操作方式:

Binder binder = Binder.get(environment);
Bindable<FooProperties> bindable = Bindable.of(XxxProperties.class);
BindResult<FooProperties> bindResult = binder.bind("prefix", bindable);
FooProperties fooProperties = bindResult.get();

或者通过反射的方式获取
其中type指的是FooProperties.class

Class<?> binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder");
Class<?> bindableClass = Class.forName("org.springframework.boot.context.properties.bind.Bindable");
Binder_get_Method = binderClass.getMethod("get", Environment.class);
Binder_bind_Method = binderClass.getMethod("bind", String.class, bindableClass);

Bindable_of_Method = Class.forName("org.springframework.boot.context.properties.bind.Bindable")
	.getMethod("of", Class.class);

BindResult_orElse_Method = Class.forName("org.springframework.boot.context.properties.bind.BindResult")
	.getMethod("orElse", Object.class);
Object binder = Binder_get_Method.invoke(null, environment);
Object bindable = Bindable_of_Method.invoke(null, type);
Object bindResult = Binder_bind_Method.invoke(binder, prefix, bindable);
BindResult_orElse_Method.invoke(bindResult, type.newInstance());

上面是获取environment对象下的具体属性值,可以设置前缀的,并且映射到具体PropertiesSource对象类中

再结合接口 ApplicationListener 的抽象方法

/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	void onApplicationEvent(ApplicationEnvironmentPreparedEvent event);
/**
 * 通过对象event可以获取environment对象
 * event.getEnvironment();
 */

就可以实现在environment对象类初始化完全之前就能提前获取对应的属性值,并映射到具体的propertiesSource类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值