可以自行定义一个配置类以及一个工具类,使用注解@Configuration,配置类在系统启动时会自动运行,装载环境信息,(这里为所有的配置信息,都会装载)
工具类会读取配置类载入的信息,返回需要的值。
代码如下:
@Configuration
public class PropertiesConfig {
@Resource
private Environment env;
@PostConstruct
public void setProperties() {
PropertiesUtil.setEnvironment(env);
}
}
public class PropertiesUtil {
private static Environment env = null;
public static void setEnvironment(Environment env) {
PropertiesUtil.env = env;
}
public static String getProperty(String key) {
String result="";
try {
result= URLDecoder.decode(PropertiesUtil.env.getProperty(key), "UTF-8") ;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
}
使用方法:
PropertiesUtil.getProperty("yy.file.rootpath")红色部分为application.properties中的属性名称