环境
- ssm框架
- jdk1.8
- IntelliJ IDEA 2019.1.2
- maven-3.6.1
项目结构如图
方法
我们用三种不同的方法读取config.properties配置文件
第一种方法在spring_mvc.xml编写一下配置
<context:property-placeholder location="classpath:properties/config.properties" ignore-unresolvable="true" file-encoding="GBK"/>
- ignore-unresolvable=“true” :配置文件 找 不 到 对 应 占 位 符 的 值 不 会 报 错 , 会 直 接 赋 值 ′ {}找不到对应占位符的值 不会报错,会直接赋值' 找不到对应占位符的值不会报错,会直接赋值′{}’;如果设为false,会直接报错Could not resolve placeholder ‘key’ in string value${key1}。 设置它为true的主要原因,是一个xml中有多个配置文件时的情况
- file-encoding=“GBK” 根据自己properties编码格式设置,我的config.properties为GBK
以下配置和上面等效
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:properties/config.properties</value>
</list>
</property>
<property name="fileEncoding" value="GBK"/>
</bean>
注意:你的spring_mvc.xml文件一定要有以下配置
<!-- 扫描web相关的bean -->
<context:component-scan base-package="com.demo.controller" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
第二种方法在spring_mvc.xml编写一下配置
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<!-- 这里是PropertiesFactoryBean类,它也有个locations属性,也是接收一个数组,跟上面一样 -->
<property name="locations">
<array>
<value>classpath:properties/config.properties</value>
</array>
</property>
<!-- 设置编码格式 -->
<property name="fileEncoding" value="GBK"></property>
</bean>
第三种方法编写一个工具类用流读取文件
**
* 文件获取工具类
*/
public class PropertyUtil {
private static final Logger logger = LoggerFactory.getLogger(PropertyUtil.class);
private static Properties props;
static {
loadProps();
}
synchronized static private void loadProps() {
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
InputStreamReader reader=null;
try {
/**
* 通过类加载器在classPath目录下获取资源.并且是以流的形式
* getClassLoader()是获取当前的类加载器
* getResourceAsStream(path)是用来获取资源的
*/
in = PropertyUtil.class.getClassLoader().getResourceAsStream("properties/config.properties");
reader = new InputStreamReader(in,"gbk");
props.load(reader);
} catch (FileNotFoundException e) {
logger.error("config.properties文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if (null != reader) {
reader.close();
}
if (null != in) {
in.close();
}
} catch (IOException e) {
logger.error("jdbc.properties文件流关闭出现异常");
}
}
logger.info("加载properties文件内容完成...........");
logger.info("properties文件内容:" + props);
}
public static String getProperty(String key) {
if (null == props) {
loadProps();
}
return props.getProperty(key);
}
public static String getProperty(String key, String defaultValue) {
if (null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}
}
具体类中应用
@Controller
@RequestMapping("user")
public class UserController {
Logger logger= LoggerFactory.getLogger(UserController.class);
//第一种方法获取值
@Value("${name}")
private String firstName;
@Value("${type}")
private String firstType;
@Value("${num}")
private String firstNum;
//第二种方法获取值
@Value("#{prop.name}")
private String twoName;
@Value("#{prop.type}")
private String twoType;
@Value("#{prop.num}")
private String twoNum;
/**
* 第一种方法测试
* @return
*/
@RequestMapping("first")
@ResponseBody
public Object getProperyFirst() {
Map<String,Object> firstResult=new HashMap<>();
firstResult.put("firstName",firstName);
firstResult.put("firstType",firstType);
firstResult.put("firstNum",firstNum);
return firstResult;
}
/**
* 第2种方法测试
* @return
*/
@RequestMapping("two")
@ResponseBody
public Object getProperyTwo() {
Map<String,Object> twoResult=new HashMap<>();
twoResult.put("twoName",twoName);
twoResult.put("twoType",twoType);
twoResult.put("twoNum",twoNum);
return twoResult;
}
/**
* 第3种方法测试
* @return
*/
@RequestMapping("third")
@ResponseBody
public Object getProperyThird( ) {
String thirdName=PropertyUtil.getProperty("name", "defaultValue");
String thirdType=PropertyUtil.getProperty("type", "defaultValue");
String thirdNum=PropertyUtil.getProperty("num", "defaultValue");
Map<String,Object> twoResult=new HashMap<>();
twoResult.put("thirdName",thirdName);
twoResult.put("thirdType",thirdType);
twoResult.put("thirdNum",thirdNum);
return twoResult;
}
}
测试结果
第一种方法结果
第2种方法结果
第3种方法结果
建议用第三种方法。
如果需要了解跟多读取配置文件的方法请点击这儿