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.PropertiesFactoryBeanorg.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的实例,然后打印出来,运行程序会输出配置文件中配置的值。

你可以下载demo项目的源码。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值