有时我们想要修改引入jar包配置,例如第三方jar包。那么我们必须自定义配置去覆盖原有jar包属性。
Springboot提供了扩展接口EnvironmentPostProcessor
自定义配置文件加载优先级:
- 相对路径,放在tomcat服务器同一级目录,优先级最高
- 绝对路径,根据配置的路径加载配置文件,优先级第二
- 默认方式,properties文件放在resources文件夹下,优先级排第三
1.实现EnvironmentPostProcessor接口,加载自定义配置文件
package com.zmx.common.common.config.shardingsphere;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import java.io.IOException;
import java.util.Properties;
/**
* @Description: 自定义配置文件 在application之前注入环境中
* @ClassName: MyEnvironmentPostProcessor
* @Author zhaomxr
* @Date 2021-12-10 09:47
*/
@RefreshScope
@Slf4j
@ConditionalOnProperty(name = "application.datasource.type", havingValue = "shardingsphere", matchIfMissing = false)
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {
private final Properties properties = new Properties();
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
try {
//自定义配置文件
String[] profiles = {"shardingsphere.properties"};
if (profiles != null && profiles.length > 0) {
//循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
}
} catch (Exception e) {
log.error("加载自定义环境配置文件失败!", e);
}
}
/**
* 加载单个配置文件
* @param resource
* @return
*/
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
try {
//从输入流中加载一个Properties对象
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
} catch (IOException ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}
2.在resource目录下新增META-INF文件夹,在文件加下新建spring.facories文件,添加上如下配置
org.springframework.boot.env.EnvironmentPostProcessor=com.zmx.common.common.config.shardingsphere.MyEnvironmentPostProcessor