Spring 依赖注入:自动注入properties文件中的配置
在很多情况下我们需要在配置文件中配置一些属性,然后注入到bean中,Spring提供了org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer
类,可以方便我们使用注解直接注入properties文件中的配置。
下面我们看下具体如何操作:
首先要新建maven项目,并在pom文件中添加spring依赖,如下pom.xml文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.outofmemory</groupId>
<artifactId>hellospring.properties.annotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>hellospring.properties.annotation</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework-version>3.0.0.RC2</org.springframework-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
</dependencies>
</project>
要自动注入properties文件中的配置,需要在spring配置文件中添加org.springframework.beans.factory.config.PropertiesFactoryBean
和org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer
的实例配置:
如下spring配置文件appContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd ">
<!-- bean annotation driven -->
<context:annotation-config />
<context:component-scan base-package="cn.outofmemory.hellospring.properties.annotation">
</context:component-scan>
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:application.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
</beans>
在这个配置文件中我们配置了注解扫描,和configProperties
实例和propertyConfigurer
实例。这样我们就可以在java类中自动注入配置了,我们看下java类中如何做:
package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MySQLConnectionInfo {
@Value("#{configProperties['mysql.url']}")
private String url;
@Value("#{configProperties['mysql.userName']}")
private String userName;
@Value("#{configProperties['mysql.password']}")
private String password;
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
}
自动注入需要使用@Value注解,这个注解的格式#{configProperties['mysql.url']}
其中configProperties是我们在appContext.xml中配置的beanId,mysql.url是在properties文件中的配置项。
properties文件的内容如下:
mysql.url=mysql's url
mysql.userName=mysqlUser
mysql.password=mysqlPassword
最后我们需要测试一下以上写法是否有问题,如下App.java文件内容:
package cn.outofmemory.hellospring.properties.annotation;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
ApplicationContext appContext = new ClassPathXmlApplicationContext("appContext.xml");
MySQLConnectionInfo connInfo = appContext.getBean(MySQLConnectionInfo.class);
System.out.println(connInfo.getUrl());
System.out.println(connInfo.getUserName());
System.out.println(connInfo.getPassword());
}
}
在main方法中首先声明了appContext,然后获得了自动注入的MySQLConnectionInfo的实例,然后打印出来,运行程序会输出配置文件中配置的值。
-------------------------------------------------------------
pring方便我们的项目快速搭建,功能强大,自然也会是体系复杂!
这里说下配置文件properties管理的问题。
一些不涉及到代码逻辑,仅仅只是配置数据,可以放在xxxx.properties文件里面,项目功能复杂的时候,往往properties文件很多,这时,就比较容易让人困惑,有些properties的文件内容总是加载不起来,应用启动时,就不断爆出错误,说某某参数加载失败,这个是什么原因呢?
其实,这个是spring配置的时候,org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer这个bean只会被加载一次。在spring的xml配置文件中,多处出现这个bean的配置,spring加载的时候,只会加载第一个,后面的就加载不了。
如何解决呢?其实很简单,比如我的一个应用中,就有internal.properties和jdbc.properties两个文件。按下面这种方式就可以解决:
1 <bean id="configRealm" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 2 <property name="locations"> 3 <list> 4 <value>classpath:conf/internal.properties</value> 5 <value>classpath:conf/jdbc.properties</value> 6 </list> 7 </property> 8 </bean> 9 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 10 <property name="properties" ref="configRealm"/> 11 </bean>
若有多个,可以在list中类似红色部分添加就可以了!
在这里,再多说一点,xml的配置问题,当然,不是功能问题,而是习惯问题!
大的基于spring的项目,往往有很多xml配置文件,比如DAO的,比如权限shiro的配置,比如redis的配置等等,在web.xml中的context-param字段,可以如下配置:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>classpath:conf/spring-dao.xml,classpath:conf/spring-servlet.xml</param-value> 4 </context-param>
但是,更好的办法,是将一些应用模块的xml配置通过import resource的方式放在一个xml文件中,例如applicationContext.xml。比如,我的应用applicationContext.xml文件的内容:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" 5 xsi:schemaLocation=" 6 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 7 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 8 9 <bean id="configRealm" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> 10 <property name="locations"> 11 <list> 12 <value>classpath:conf/internal.properties</value> 13 <value>classpath:conf/jdbc.properties</value> 14 </list> 15 </property> 16 </bean> 17 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> 18 <property name="properties" ref="configRealm"/> 19 </bean> 20 21 <import resource="applicationContext-springdata.xml"/> 22 <import resource="applicationContext-security.xml"/> 23 <import resource="applicationContext-ehcache.xml"/> 24 <import resource="applicationContext-task.xml"/> 25 <import resource="applicationContext-external.xml"/> 26 <import resource="applicationContext-message.xml"/> --> 27 </beans>
这个applicationContext.xml可以在web.xml中的context-param配置部分加载,如下:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value>classpath:conf/applicationContext.xml</param-value> 4 </context-param>
这样子,就会使得项目的配置文件结构非常的清晰!