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>
Spring框架中的`@Value`注解用于将配置值注入到字段或方法参数中。它的原理是通过`PropertySourcesPlaceholderConfigurer`和`PropertyResolver`来实现的。 具体步骤如下: 1. 在Spring配置文件中配置`PropertySourcesPlaceholderConfigurer`。这个bean将负责解析和替换属性占位符。 2. `PropertySourcesPlaceholderConfigurer`会扫描所有的配置文件,包括`application.properties`、`application.yml`等,并将其中的属性加载到一个属性源中。 3. 当Spring容器初始化时,`PropertySourcesPlaceholderConfigurer`会将配置文件中的属性值替换为真实的值。 4. 当使用`@Value`注解时,Spring使用`PropertyResolver`接口的实现类来解析配置值。默认情况下,使用的是`Environment`作为`PropertyResolver`的实现类。 5. `Environment`对象会从属性源中获取配置值,并将其注入到对应的字段或方法参数中。 通过以上步骤,Spring就能够将配置文件中的值注入到使用了`@Value`注解的字段或方法参数中。 下面是一个示例: ```java import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; @Component @PropertySource("classpath:application.properties") public class MyComponent { @Value("${my.property}") private String myProperty; // ... } ``` 在上述示例中,通过`@Value("${my.property}")`将配置文件中名为`my.property`的属性值注入到`myProperty`字段中。 请注意,为了使`@Value`注解生效,需要确保已正确配置了相关的配置文件,并且在Spring配置中启用了对`@Value`的解析。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值