文章目录
前言
SpringBoot项目中,bean可以通过@value注入方式获取属性配置.但是有时候我们希望用常量来获取属性,保证项目任意位置都能通过常量对象获取属性。
正文
1. 属性获取工具类
1. 1 SpringPropertyResourceReader
定义工具类SpringPropertyResourceReader 实现ApplicationContextAware接口,获取上下文属性
/**
* 读取spring容器加载的属性配置文件
* @author myron
*/
@Component
public class SpringPropertyResourceReader implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/** 配置文件中原始属性带占位符*/
private static Properties properties = new Properties();
private static PropertySourcesPropertyResolver propertySourcesPropertyResolver = null;
/** 获取上下文属性*/
private static void init() {
try {
Environment env = applicationContext.getEnvironment();
StandardEnvironment standardServletEnvironment = (StandardEnvironment) env;
MutablePropertySources mutablePropertySources = standardServletEnvironment.getPropertySources();
Iterator<PropertySource<?>> iterator = mutablePropertySources.iterator();
while (iterator.hasNext()) {
PropertySource propertySource = iterator.next();
Object source = propertySource.getSource();
if (source instanceof Properties) {
Properties prop = (Properties) propertySource.getSource();
properties.putAll(prop);
}
}
propertySourcesPropertyResolver = new PropertySourcesPropertyResolver(standardServletEnvironment.getPropertySources());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* 获取属性文件中原始属性值,可能含有变量
* @param propertyName
* @return
*/
public static String getPropertyRaw(String propertyName) {
return properties.getProperty(propertyName);
}
/**
* 生效属性真实值
* @param key
* @return
*/
public static String getProperty(String key) {
return propertySourcesPropertyResolver.getProperty(key);
}
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
applicationContext = arg0;
init();
}
}
1.2 配置属性(示例)
### cas server config
cas.server.url.prefix = https://portal.myron.com/cas
cas.server.url.login = ${cas.server.url.prefix}/login
cas.server.url.logout = ${cas.server.url.prefix}/logout
1.3 使用属性常量(示例)
package sample.shiro.constants;
import sample.shiro.config.SpringPropertyResourceReader;
/**
* cas属性配置常量
*/
public class CasConstants {
/** cas服务地址*/
public static final String SERVER_PREFIX = SpringPropertyResourceReader.getProperty("cas.server.url.prefix");
/** cas登入服务地址*/
public static final String SERVER_LOGIN = SpringPropertyResourceReader.getProperty("cas.server.url.login");
/** cas注销服务地址*/
public static final String SERVER_LOGOUT = SpringPropertyResourceReader.getProperty("cas.server.url.logout");
}
现在就可以通过访问CasConstants.SERVER_LOGIN_URL 以常量形式在springboot项目中使用。
1.4 精简版(补充)
只获取有效属性
package com.easy.common.core.aware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.StringUtils;
/**
* 读取spring容器加载的属性配置文件
* @author myron
*/
public class SpringPropertyResourceReader implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(SpringPropertyResourceReader.class);
private static PropertySourcesPropertyResolver propertySourcesPropertyResolver = null;
private static void init(ApplicationContext applicationContext) {
try {
Environment env = applicationContext.getEnvironment();
StandardEnvironment standardServletEnvironment = (StandardEnvironment) env;
propertySourcesPropertyResolver = new PropertySourcesPropertyResolver(standardServletEnvironment.getPropertySources());
} catch (Exception e) {
logger.error("SpringPropertyResourceReader init error.",e);
}
}
public static String getProperty(String propertyName) {
return propertySourcesPropertyResolver.getProperty(propertyName);
}
public static String getProperty(String propertyName, String defaultValue) {
String value = propertySourcesPropertyResolver.getProperty(propertyName);
return !StringUtils.isEmpty(value) ? value : defaultValue;
}
@Override
public void setApplicationContext(ApplicationContext arg0) throws BeansException {
logger.info("--------SpringPropertyResourceReader init-------");
init(arg0);
}
}
测试
System.out.println(SpringPropertyResourceReader.getProperty("user.home")); // C:\Users\zhangsan
System.out.println(SpringPropertyResourceReader.getProperty("spring.application.name")); // demo-application
1.5 hutool提供SpringUtil
发现hutool已经将上面类似功能集成了,可以直接用。
-
maven依赖
<hutool-all.version>5.7.19</hutool-all.version> <!--hutool工具类--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>${hutool-all.version}</version> </dependency>
-
配置类开启@EnableSpringUtil 注解 (注册成bean才能获取spring的资源)
-
使用SpringUtil工具类
// 常量类中引用 public class AppConstants { /** */ public static final String BASE_DIR = System.getProperty("user.home") + File.separator + "." + SpringUtil.getApplicationName() + File.separator; }
// 打印环境变量
System.out.println(SpringUtil.getApplicationName());
System.out.println(SpringUtil.getProperty(“user.home”));