使用spring注入项目的配置文件

以前我们会写一个listener (implements ServletContextListener),在项目启动时,读取properties文件,存入一个全局对象中,以便后续使用。这样需要我们写很多的代码,有了spring,一切变得简单起来。

我们知道的用法

在applicationcontext.xml中可以这么使用

 <bean id="propertyConfigurer"  
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
    <property name="location" value="classpath:jdbc.properties" />  
</bean>  
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
    destroy-method="close">  
    <property name="driverClassName" value="${driver}" />  
    <property name="url" value="${url}" />  
    <property name="username" value="${username}" />  
    <property name="password" value="${password}" />  
</bean>  

可能很多人不知道

<bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath*:initial.properties</value>
            <value>/WEB-INF/classes/redis.properties</value>
        </list>
    </property>
    <property name="fileEncoding" value="utf-8" />
</bean>


public class TestController {
    @Value("${common.baidu_ak}")
    String baidu_ak;
    @Value("${address}")
    String address;
    @Value("${lon}")
    String lon;
    ...
文章目录
  1. 1. 我们知道的用法
  2. 2. 可能很多人不知道
|