有没有想过,不用@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类。