今天结合看到的各位大神的微博以一篇关于springmvc 支持properties文件的文章
1.背景
spring 3.2开始支持配置注解的方式使用properties文件,4.0时支持多文件配置;这里以spring-4.0 为例介绍框架使用properties文件的方式。
2.引用方式
(一) 配置文件中使用:
//配置文件中必须引入响应的命名空间
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<context:property-placeholder location="classpath:db.properties" />
//使用实例:
<property name="username" value="${db.username}" />
(二)采用(一)中的配置
在controller、service中引用
@Autowired //方式二,env里有系统自动注入的对象
private Environment env;//使用properties 中的变量
env.getproperty("db.username");
(三)采用将properties文件转换为系统对象的方式
//properties
@Configuration
@PropertySource(value="classpath:db.properties")
public class Config {
@Value(value="${db.username}")
public String username;
@Value(value="${db.password}")
public String password;
@Bean
public static PropertySourcesPlaceholderConfigurer initProperty(){//必须的
return new PropertySourcesPlaceholderConfigurer();
}
}
在具体的controller 中使用注解引用
@Autowired
private Config c;
(四)采用配置文件注入的方式
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:db.properties" />
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
//使用
@Value("#{configProperties['db.username']}")//注意是configProperties,#,{}等符号要对
private String username;
(五)采用util:properties
<util:properties location="classpath:db.properties" id="sys" />
//引用
@Value("#{sys['db.username']}")//注意是sys是对应的
private String un;