Spring Boot指定外部application.properties配置文件啟動(實踐)

1.修改pom.xml,過濾src/main/resources目錄下.properties文件


Spring Boot指定外部application.properties配置文件啟動(實踐)

pom.xml

pom.xml代碼:

<code> <build>
<finalname>XXXX/<finalname>
<plugins>
<plugin>
<groupid>org.springframework.boot/<groupid>
<artifactid>spring-boot-maven-plugin/<artifactid>
/<plugin>
/<plugins>
<resources>
<resource>
<directory>src/main/resources/<directory>
<excludes>
<exclude>**/*.properties/<exclude>
/<excludes>
/<resource>
/<resources>
/<build>/<code>


2.在resources目錄下創建META_INF/spring.factories文件(注意META_INF文件夾也是要創建的)


Spring Boot指定外部application.properties配置文件啟動(實踐)

spring.factories

spring.factories內容:

<code>org.springframework.boot.env.EnvironmentPostProcessor=com.config.LocalSettingsEnvironmentPostProcessor
/<code>


3.新建LocalSettingsEnvironmentPostProcessor.java加載外部屬性文件application.properties


Spring Boot指定外部application.properties配置文件啟動(實踐)

LocalSettingsEnvironmentPostProcessor


LocalSettingsEnvironmentPostProcessor.java代碼如下:

<code>package com.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.File;
import java.io.IOException;
import java.util.Properties;

/**
* @author 光州程序猿
* @version 1.0
*/
public class LocalSettingsEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final String LOCATION = "C:\\\\Users\\\\Desktop\\\\application.properties";

@Override
public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
File file = new File(LOCATION);
try {
MutablePropertySources propertySources = configurableEnvironment.getPropertySources();
Properties properties = loadProperties(file);
propertySources.addFirst(new PropertiesPropertySource("Config", properties));
} catch (Exception e) {
e.printStackTrace();
}
}


private Properties loadProperties(File f) {
FileSystemResource resource = new FileSystemResource(f);
try {
return PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException ex) {
throw new IllegalStateException("Failed to load local settings from " + f.getAbsolutePath(), ex);
}
}
}
/<code>


啟動SpringBoot項目,指定外部application.properties啟動成功。


Spring Boot指定外部application.properties配置文件啟動(實踐)

啟動結果


分享到:


相關文章: