背景: Spring、SpringMVC4.0.2、Mybatis3.2.6、JDK1.8、tomcat8、maven3.3.9、MyEclipse2013
项目结构:
demo.properties:
方法一: springmvc.xml context:property-placeholder标签引入
<context:component-scan base-package="com" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<context:property-placeholder location="classpath:demo.properties" ignore-unresolvable="true"/>
注意: 若加上红色部分,只能在controller注入service无法注入,反之controller、service均能注入
controller、service注入写法一致
@Controller
@RequestMapping("/demo")
public class DemoController {
@Autowired
UserService userService;
@Value("${demo.user}")
private String user;
}
方法二: <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 注入
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<!-- 引入properties配置文件 方式一 -->
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:demo.properties</value>
</list>
</property>
</bean>
注意: class注入写法如方法一
方法三: 仿方法二,class自定义 。service层可直接注解取值
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="propertyConfigurer2" class="com.prop.PropertyConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath:demo.properties</value>
</list>
</property>
</bean>
PropertyConfigurer.class
package com.prop;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
public class PropertyConfigurer extends PropertyPlaceholderConfigurer {
private Properties props;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
throws BeansException {
super.processProperties(beanFactoryToProcess, props);
this.props = props;
}
public String getProperty(String key){
return this.props.getProperty(key);
}
public String getProperty(String key, String defaultValue) {
return this.props.getProperty(key, defaultValue);
}
public Object setProperty(String key, String value) {
return this.props.setProperty(key, value);
}
}
controller: @autowire注入bean getProperty(key)取值
@Controller
@RequestMapping("/demo")
public class DemoController {
@Autowired
PropertyConfigurer prop;
@RequestMapping("/list")
public ModelAndView list(){
String user = prop.getProperty("demo.user");
System.out.println("controller user: " + user);
......
service:
@Service("userService")
public class UserService {
@Autowired
UserDao userDao;
@Value("${demo.user}")
private String user;
方法四: @PropertySource @autowire注入Environment
@Controller
@RequestMapping("/demo")
@PropertySource(value={"classpath:demo.properties"})
public class DemoController {
@Autowired
private Environment environment;
@RequestMapping("/list")
public ModelAndView list(){
String user = environment.getProperty("demo.user");
System.out.println("controller user: " + user);
.......
方法五: <bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> bean注入
class文件注入方式@Value(value="#{demoProp[demo_user]}")
需要注意的是,PropertiesFactoryBean实现了 FactoryBean<Properties>,用的是Properties.class解析配置文件。
所以当properties文件中用小数点"."命名key时(如demo.user),class注入时需把key加上单引号(#{demoProp['demo.user'])
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="location" value="classpath:jdbc.properties" />
</bean>
<bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:demo.properties</value>
</list>
</property>
<!-- 设置编码格式 -->
<property name="fileEncoding" value="UTF-8"></property>
</bean>
或者
<bean id="demoProp" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:demo.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
<!-- 设置编码格式 -->
<property name="fileEncoding" value="UTF-8"></property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="properties" ref="demoProp" />
</bean>
上述写法既可用#{demoProp[demo_user]} ,亦可用${demo_user}。
方法六: <util:properties />注入
需在xml文件加上 xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation=http://www.springframework.org/schema/util
classpath:/org/springframework/beans/factory/xml/spring-util-4.0.xsd
在此说明下,由于是在myeclipse下,弹出安全证书点了否,查找半天资料引入本地xsd文件 /捂脸/捂脸/捂脸
附上网络版 http://www.springframework.org/schema/util/spring-util-4.0.xsd
<util:properties id="demoProp" location="classpath:demo.properties"/>
注意: 注入方式参考方法五
方法七: utils.class读取配置文件
public class PropertiesUtils {
private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
private static final String FILE_NAME = "demo.properties";
private static Properties props;
static{
loadProps();
}
synchronized static private void loadProps(){
logger.info("开始加载properties文件内容.......");
props = new Properties();
InputStream in = null;
try {
//第一种,通过类加载器进行获取properties文件流
// in = PropertiesUtils.class.getClassLoader().getResourceAsStream(FILE_NAME);
//第二种,通过类进行获取properties文件流
in = PropertiesUtils.class.getResourceAsStream("/" + FILE_NAME);
props.load(in);
} catch (FileNotFoundException e) {
logger.error(FILE_NAME + "文件未找到");
} catch (IOException e) {
logger.error("出现IOException");
} finally {
try {
if(null != in) {
in.close();
}
} catch (IOException e) {
logger.error(FILE_NAME + "文件流关闭出现异常");
}
}
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);
}
}
用法:
String user = PropertiesUtils.getProperty("demo.user");
至此,所有方式记录完毕。
源码下载地址: https://download.csdn.net/download/weixin_42803662/10680879
参考资料: