Spring的@PropertySource + Environment,@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value配合使用

@PropertySource注解可以配置读取单个或多个配置文件:

单个配置文件:

@PropertySource(value = "classpath:spring/config.properties")

多个配置文件:

@PropertySource(value = {"classpath:spring/config.properties","classpath:spring/news.properties"})

 

@PropertySource注解使用有两种方式:

1、@PropertySource + Environment,通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。

2、@PropertySource(PropertySourcesPlaceholderConfigurer)+@Value

 

示例1:@PropertySource + Environment 

在spring3.1中(不是spring3.0)还可以这样:

package com.dxz.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = "com.dxz.config")
@PropertySource(value = "classpath:spring/config.properties")
public class ServiceConfiguration { 

    @Autowired 
    Environment environment; 

    public ServiceConfiguration() {
        System.out.println("ServiceConfiguration zheli");
    }
    
    //@Bean
    public javax.sql.DataSource dataSource(){ 
        String user = this.environment.getProperty("ds.user");
        System.out.println(user);
        return null;
    } 
}

配置文件config.properties:

key1=abc
key2=aaaaaaaaaaaaaaaaaaaa
key3=bbbbbbbbbbbbbbbbbbbbbbbbbbb
key4=cccccccccc
ds.user=admin

测试类:

复制代码
package com.dxz.config;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test {
    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(ServiceConfiguration.class);
        
        ServiceConfiguration hc2 = (ServiceConfiguration) context.getBean("serviceConfiguration");
        hc2.dataSource();
        
    }
}
复制代码

结果:

十一月 02, 2017 10:20:43 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3f91beef: startup date [Thu Nov 02 10:20:43 CST 2017]; root of context hierarchy
ServiceConfiguration zheli
admin

示例2: @PropertySource(PropertySourcesPlaceholderConfigurer)+@Value

创建Spring配置Class

package com.dxz.config2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration  
@ComponentScan(basePackages = "com.dxz.config2")
public class AppConfigMongoDB {  
  
    @Bean  
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {  
        return new PropertySourcesPlaceholderConfigurer();  
    }  
    
} 

 

package com.dxz.config2;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value = "classpath:spring/config.properties")
public class MongoDBConfig {
    //1.2.3.4  
    @Value("${key1}")  
    private String mongodbUrl;  
  
    //hello  
    @Value("${ds.user}")  
    private String defaultDb;

    @Override
    public String toString() {
        return "MongoDBConfig [mongodbUrl=" + mongodbUrl + ", defaultDb=" + defaultDb + "]";
    }
}

测试类:

package com.dxz.config2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test5 {
    
    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfigMongoDB.class);
        
        MongoDBConfig ac = (MongoDBConfig)context.getBean("mongoDBConfig");
        System.out.println(ac);
        
    }
}

结果:

十一月 02, 2017 11:54:06 上午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3f91beef: startup date [Thu Nov 02 11:54:06 CST 2017]; root of context hierarchy
MongoDBConfig [mongodbUrl=abc, defaultDb=admin]

 

 

spring4版本

在Spring 4版本中,Spring提供了一个新的注解——@PropertySources,从名字就可以猜测到它是为多配置文件而准备的。

package com.dxz.config3;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;

@Component
@PropertySources({
@PropertySource("classpath:db.properties"),
//@PropertySource(value="classpath:db.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:spring/config.properties")
})
public class AppConfig {
    @Value("${key1}")
    private String key1;
    
    @Value("${key2}")
    private String key2;

    @Override
    public String toString() {
        return "AppConfig [key1=" + key1 + ", key2=" + key2 + "]";
    }
    
}

spring的配置class

package com.dxz.config3;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration  
@ComponentScan(basePackages = "com.dxz.config3")
public class AppConfiguation {  
  
    @Bean  
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {  
        return new PropertySourcesPlaceholderConfigurer();  
    }  
    
} 

测试类:

package com.dxz.config3;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;


public class Test6 {
    
    public static void main(String[] args) {

        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfiguation.class);
        
        AppConfig ac = (AppConfig)context.getBean("appConfig");
        System.out.println(ac);
        
    }

}

结果:

另外在Spring 4版本中,@PropertySource允许忽略不存在的配置文件。先看下面的代码片段:

@Configuration
@PropertySource("classpath:missing.properties")
public class AppConfig {
    //something
}

如果missing.properties不存在或找不到,系统则会抛出异常FileNotFoundException。

Caused by: java.io.FileNotFoundException: 
		class path resource [missiong.properties] cannot be opened because it does not exist

幸好Spring 4为我们提供了ignoreResourceNotFound属性来忽略找不到的文件

package com.dxz.config3;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.stereotype.Component;

@Component
@PropertySources({
//@PropertySource("classpath:db.properties"),
@PropertySource(value="classpath:db.properties", ignoreResourceNotFound=true),
@PropertySource("classpath:spring/config.properties")
})
public class AppConfig {
    @Value("${key1}")
    private String key1;
    
    @Value("${key2}")
    private String key2;

    @Override
    public String toString() {
        return "AppConfig [key1=" + key1 + ", key2=" + key2 + "]";
    }
    
}

最上面的AppConfiguation 的配置代码等于如下的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-4.0.xsd
    http://www.springframework.org/schema/context   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
    <context:component-scan base-package="com.9leg.java.spring"/>
 
    <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
          <list>
            <value>classpath:spring/config.properties</value>
          </list>
        </property>
      </bean>
</beans>

 

posted on 2012-11-06 09:33  duanxz  阅读(7419)  评论(1编辑  收藏  举报