Spring 支持在代码中使用@Value注解的方式获取properties文件中的配置值,从而大大简化了读取配置文件的代码。
使用方法如下:
假如有一个参数配置文件test.properties
#数据库配置
database.type=sqlserver
jdbc.url=jdbc:sqlserver://192.168.1.105;databaseName=test
jdbc.username=test
jdbc.password=test
1、先在配置文件中声明一个bean
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:test.properties</value>
</array>
</property>
</bean>
2、在代码中使用@Value()注解
@Value("${jdbc.url}")
private String url = "";
这样就可以获取到配置文件中的数据库url参数值并赋给变量url了,成员变量url不需要写get、set方法。
当然如果你想在配置文件的参数值上进行修改后再附上去,可以写个set方法,把@Value注解改到set方法上,例如:
@Value("${jdbc.url}")
public void setUrl(String url) {
this.url= "http://" + url;
}
3、不仅如此,还可以直接在spring的配置文件中使用${XXX}的方式注入,例如:
<!-- 数据源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
补充:
之前写的bean直接指向了spring默认的PropertyPlaceholderConfigurer类,其实也可以重写它的一些方法,来满足自己的需求。步骤就是自己定义一个子类继承PropertyPlaceholderConfigurer,然后重写里面的方法(mergeProperties()、loadProperties(Properties props)等),例如:
package com.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
/**
* Spring参数配置加载
*/
public class MyPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
//获取配置文件的参数和参数值
protected Properties mergeProperties() throws IOException {
//调用父类的该方法获取到参数和参数值
Properties result = super.mergeProperties();
String url = result.getProperty("jdbc.url");
//对jdbc.url参数的值前面加上"http://"后再放进去,就实现了参数值的修改
result.setProperty("jdbc.url", "http://"+url);
}
//加载配置文件
protected void loadProperties(Properties props) throws IOException {
if(XXX){//如果满足某个条件就去加载另外一个配置文件
File outConfigFile = new File("配置文件的全路径");
if(outConfigFile.exists()){
props.load(new FileInputStream(outConfigFile));
}else{
super.loadProperties(props);
}
}else{
//否则就继续加载bean中定义的配置文件
super.loadProperties(props);
}
}
}
然后之前声明的bean的class指向它就行了,如下:
<bean class="com.test.MyPropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:test.properties</value>
</array>
</property>
</bean>