配置文件
需求
針對不同環境下,可以配置不同的配置文件,如log-dev.properties、log-test.properties。
Spring環境
采用spring.profiles.active屬性來區分不同的應用環境。
配置類
@Data
@Component
@ConfigurationProperties(prefix = "log")
@PropertySource(name = "log", value = "classpath:log-${spring.profiles.active:}.properties", factory = SystemPropertySourceFactory.class)
public class LogConfig implements Serializable {
private static final long serialVersionUID = 1L;
private String host;
private int port;
private int maxThreads = 20;
private int saveMode = 0;
private boolean saveLog = true;
private String namesrvAddr;
private String producerGroupName;
private String instanceName;
private int sendTimeout;
}
若spring.profiles.active為空,則該值為空字符串。
PropertySourceFactory
/**
* 針對自定義配置文件的一個多環境配置邏輯
*
*/
public class SystemPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource)
throws IOException {
String fileSuffix = "";
try {
String filename = resource.getResource().getFilename();
fileSuffix = filename.substring(filename.lastIndexOf("."));
resource.getResource().getFile();
return new ResourcePropertySource(name, resource);
} catch (Exception e) {
InputStream inputStream = SystemPropertySourceFactory.class.getClassLoader()
.getResourceAsStream(name + fileSuffix);
//轉成resource
InputStreamResource inResource = new InputStreamResource(inputStream);
return new ResourcePropertySource(new EncodedResource(inResource));
}
}
}
若spring.profiles.active=dev有配置,但是沒有這個配置文件(例:log-dev.properties),則默認讀取log.properties。若spring.profiles.active無配置,則默認讀取log.properties。
非Spring環境
思路:將spring.profiles.active 屬性設置到System環境變量。則非Spring環境可從System環境變量中獲取該值。
@Component
public class ServerInfo implements ApplicationListener<WebServerInitializedEvent> {
private static final String SPRING_PROFILES_ACTIVE = "spring.profiles.active";
@Override
public void onApplicationEvent(WebServerInitializedEvent event) {
//設置系統變量
System.setProperty(SPRING_PROFILES_ACTIVE, this.getProfileActive());
}
/**
* 獲取spring.profiles.active屬性值
* @return
*/
public String getProfileActive() {
return env.getProperty(SPRING_PROFILES_ACTIVE, "");
}
}
