欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot加載外部配置文件實踐(properties、yml)

 更新時間:2025年09月15日 08:52:14   作者:小魚干。。  
文章介紹Spring配置加載方式,通過PropertySourceLoader接口加載properties/yml文件,利用監(jiān)聽器將配置注入Spring環(huán)境,并通過addFirst等方法控制優(yōu)先級,還說明了Spring?Boot默認配置文件加載優(yōu)先級及監(jiān)聽器配置方法

1.前言

通過PropertySourceLoader接口的實現(xiàn)類配合監(jiān)聽器實現(xiàn)加載外部的配置文件,加載properties文件使用PropertiesPropertySourceLoader,加載yml文件使用YamlPropertySourceLoader。

通過監(jiān)聽器將配置文件加載到Spring環(huán)境配置中,且可以指定優(yōu)先級。

核心是將配置文件加載PropertySource中并將其添加到spring的MutablePropertySources中,使其可以通過@value等方式獲取配置文件中的屬性值。

2.加載properties文件

1.方法一:PropertiesPropertySourceLoader

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        PropertiesPropertySourceLoader loader = new PropertiesPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("publicConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

2.方法二:PropertiesFactoryBean

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        PropertiesFactoryBean factoryBean = new PropertiesFactoryBean();
        try {
            factoryBean.setLocation(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.properties"))));
            Properties object = factoryBean.getObject();
            if(object != null){
                PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
                configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

3.加載yml文件

1.方法一:YamlPropertySourceLoader

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {

        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

2.方法二:YamlPropertiesFactoryBean

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        try {
            factoryBean.setResources(new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml"))));
            Properties object = factoryBean.getObject();
            if(object != null){
                PropertiesPropertySource propertySource = new PropertiesPropertySource("publicConfiguration",object);
                configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4.配置優(yōu)先級

通過上述代碼可以發(fā)現(xiàn)所有方法最后都是通過configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource)將封裝好的PropertySource對象加入到Spring配置中的,而都是通過調(diào)用addFirst(PropertySource  propertySource),除了addFirst還有addLast,addBefore,addAfter,這就與優(yōu)先級有關系了,先說一下addBefore和addAfter,這兩個方法參數(shù)都是String relativePropertySourceName, PropertySource<?> propertySource,意思就是要將此propertySource添加在名為relativePropertySourceName的propertySource的前邊還是后邊,放在前邊的在讀取屬性時會優(yōu)先讀取屬性值,而addFirst和addLast則是將此propertySource放在整個列表的最前或最后。

對于優(yōu)先讀取該屬性的值的解釋

例如項目中的配置文件application.yml中有屬性name: zhangsan,外部配置文件externalApplication.yml中有屬性name: lisi,通過上述任何方式將外部配置文件加載到Spring配置中后因為兩個配置文件中都有name屬性,但其值不相同,這個時候如果通過@Value("${name}")取值會取到zhangsan還是lisi呢,答案是在上述PropertySource列表中靠前的會優(yōu)先生效。

如果想讓外部的配置文件優(yōu)先則可以使用addFirst方法添加propertySource。

提到配置文件的優(yōu)先級就想起了springboot默認讀取配置文件的優(yōu)先級,參考下方說明:

優(yōu)先級依次遞減

  • 1.在執(zhí)行命令的目錄下建config文件夾,然后把配置文件放到這個文件夾下。(在jar包的同一個目錄下建config文件夾,執(zhí)行命令需要在jar包所在目錄下才行)
  • 2.直接把配置文件放到jar包的同級目錄
  • 3.在classpath下建一個config文件夾,然后把配置文件放進去。
  • 4.在classpath下直接放配置文件。

5.使用的監(jiān)聽器以及加載的時機(監(jiān)聽的事件)

無論使用那種監(jiān)聽器的實現(xiàn)類型,都需要拿到ConfigurableEnvironment這個參數(shù),可以在多個時機加載配置文件,例如environmentPrepared,contextPrepared,下面展示三種方式實現(xiàn)

方法一:

public class MyApplicationContextInitializer implements ApplicationContextInitializer {

    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            configurableApplicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

需要將該類的全限定名配置到spring.factories中

org.springframework.context.ApplicationContextInitializer=com.fkp.springboot_listener.listener.MyApplicationContextInitializer

方法二:

public class MySpringApplicationRunListener implements SpringApplicationRunListener {

    private final SpringApplication springApplication;

    private final String[] args;

    public MySpringApplicationRunListener(SpringApplication springApplication, String[] args) {
        this.springApplication = springApplication;
        this.args = args;
    }

    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("SpringApplicationRunListener....starting");
    }

    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            environment.getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....contextPrepared");
    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....contextLoaded");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....started");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener....running");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener....failed");
    }
}

需要將該類的全限定名配置到spring.factories中

org.springframework.boot.SpringApplicationRunListener=com.fkp.springboot_listener.listener.MySpringApplicationRunListener

方法三:

public class MyApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent applicationEnvironmentPreparedEvent) {
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            PropertySource<?> propertySource = loader.load("externalConfiguration", new InputStreamResource(Files.newInputStream(Paths.get("C:\\Users\\fkp12\\Desktop\\application.yml")))).get(0);
            applicationEnvironmentPreparedEvent.getEnvironment().getPropertySources().addFirst(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

需要將該類的全限定名配置到spring.factories中

org.springframework.context.ApplicationListener=com.fkp.springboot_listener.listener.MyApplicationListener

備注:通過Environment取Spring配置中的值

Environment或實現(xiàn)該接口的類可以通過多種方式獲取,例如上述ApplicationEnvironmentPreparedEvent#getEnvironment()獲取ConfigurableEnvironment

通用的一種方法是通過ApplicationContext獲取,ApplicationContext#getEnvironment(),ApplicationContext可以從Spring容器中取。

通過Environment的getProperty方法可以取Spring配置中屬性的值。

總結

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關文章

最新評論