Environment使用

Author Avatar
丁起男 01月 24,2022
  • 在其它设备中阅读本文章

Environment使用

获取配置文件数据

person:
  name: zhangsan
  age: 18

使用

@Autowired
private Environment environment;
//获取指定值
Object name = environment.getProperty("person.name");
//类型转换
Integer age = environment.getProperty("person.age", Integer.class);
//没有此值的默认值
Integer sex = environment.getProperty("person.sex", Integer.class,1);

环境

是否是指定环境

environment.acceptsProfiles("pro")

获取所有激活配置文件

environment.getActiveProfiles();

获取其它配置文件

利用spring的事件机制

public class YmlListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    //配置文件地址
    private String path;

    public YmlListener(String path){
        this.path = path;
    }
    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        //获取当前环境的Environment
        ConfigurableEnvironment environment = event.getEnvironment();
        DefaultResourceLoader loader = new DefaultResourceLoader();
        //加载解析配置文件
        YamlPropertySourceLoader ymlLoader = new YamlPropertySourceLoader();
        List<PropertySource<?>> sourceList = ymlLoader.load(path, loader.getResource(path));

        for (PropertySource<?> propertySource : sourceList) {
            //将解析的结果添加到environment
            environment.getPropertySources().addLast(propertySource);
        }

    }
}

注册监听

public static void main(String[] args) {
    SpringApplication springApplication = new SpringApplication(DatasourceDemoApplication.class);
    //添加事件监听
    springApplication.addListeners(new YmlListener("classpath:application2.yml"));
    springApplication.run(args);
}