springboot 根据不同配置文件来设定常量的值
原因:不同环境下(开发环境和正式环境)动态设置常量的值,比如将文件以绝对路径保存时,开发环境(windows系统)和正式环境(linux系统)的路径肯定是不同的,这时就需要根据配置文件来设置路径了
- 在配置文件中配置路径,然后通过import org.springframework.beans.factory.annotation包下的@Value注解获取
hdfs:
path: hdfs://192.168.2.13:9000
user: root
----------------------------------------------------------
@Value("${hdfs.path}")
private String hdfsPath;
@Value("${hdfs.user}")
private String hdfsUser
- 在配置文件中配置路径,通过注解==@ConfigurationProperties(prefix = ConfigProperties.PREFIX)
==读取配置文件中的前缀,从而获取此路径下配置的常量
# 自定义配置
ws:
logFilePath: E:/var/log/ad/pointcloud
--------------------------------分割线---------------------------------------------
// //这里相当于是将"ws"作为ConfigProperties 类,logFilePath为对应的成员变量
@Component
@ConfigurationProperties(prefix = ConfigProperties.PREFIX)
public class ConfigProperties {
public static final String PREFIX = "ws";
private String logFilePath;
public String getLogFilePath() {
return logFilePath;
}
public void setLogFilePath(String logFilePath) {
this.logFilePath = logFilePath;
}
}
- 现获取激活的配置文件,并通过实现import org.springframework.beans.factory包下的接口InitializingBean来初始化bean,从而复写afterPropertiesSet() 方法,在设置好配置文件后动态设定常量的值
@Configuration
public class FileConstant implements InitializingBean {
// public static final String FILE_DIR = "D:"+ File.separator +"las";
public static String FILE_DIR = null;
@Value("${spring.profiles.active}")
private String env;
@Override
public void afterPropertiesSet() throws Exception {
if ("dev".equals(env) || "demo".equals(env))//判断active下的配置文件后缀
FILE_DIR = "E:" + File.separator + "file";
else if ("test".equals(env))
FILE_DIR = "/data/tmpDir";
else
FILE_DIR = "/dev/nvme0n1p2";
}
}