在使用spring的时候,我们为了避免硬编码,有些变量不在java类中写死,而是采用一种可配置的方式获取,当我们的变量发生改变,我们只需要修改属性配置文件,重启项目,而不用重新编译class文件。
这里说一个@Value的用法,通过这个注解,我们可以读取属性文件里面的变量,比如这个变量为url,指定的是jdbc.url。我们来个测试。
UserDao.java
package com.xxx.springcontext.dao;
import org.springframework.beans.factory.annotation.Value;
public class UserDao {
//@Value("${jdbc.url}")
@Value("#{propertiesReader['jdbc.url']}")
private String url;
public String getAddress() {
return this.url;
}
}
UserService.java
package com.xxx.springcontext.service;
import org.springframework.beans.factory.annotation.Autowired;
import com.xxx.springcontext.dao.UserDao;
public class UserService {
@Autowired
private UserDao userDao;
public String getAddress() {
return userDao.getAddress();
}
}
jdbc.properties
jdbc.url=jdbc:mysql:///shiro?useUnicode=true&useSSL=false&characterEncoding=UTF-8
spring.xml
<context:component-scan base-package="com.xxx.springcontext">
<context:include-filter type="regex" expression="com\.xxx\.springcontext\.dao\..*"/>
<context:include-filter type="regex" expression="com\.xxx\.springcontext\.service\..*"/>
</context:component-scan>
<bean id="propertiesReader" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations" value="classpath:jdbc.properties"></property>
</bean>
单元测试类App.java
package com.xxx.springcontext;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.xxx.springcontext.service.UserService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:spring.xml"})
public class App {
@Resource
private UserService userService;
@Test
public void propTest() {
String address = userService.getAddress();
System.out.println(address);
}
}
运行结果如下:
这种配置中,我们再spring.xml文件里面配置了PropertiesFactoryBean并指定了属性文件的位置。
用法就是:
@Value("#{propertiesReader['jdbc.url']}")
其中propertiesReader是PropertiesFactoryBean的ID。这种用法还不是最简单的,最简单的用法应该是。
@Value("${jdbc.url}")
这种语法,就需要在配置文件中新增配置PreferencesPlaceholderConfigurer。
<context:component-scan base-package="com.xxx.springcontext">
<context:include-filter type="regex" expression="com\.xxx\.springcontext\.dao\..*"/>
<context:include-filter type="regex" expression="com\.xxx\.springcontext\.service\..*"/>
</context:component-scan>
<bean id="propertiesReader" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations" value="classpath:jdbc.properties"></property>
</bean>
<bean id="propConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="propertiesReader"></property>
</bean>
还会用到之前配置的PropertiesFactoryBean。