Spring的@PropertySource和@Value注解例子

来源:互联网 发布:python coroutine 编辑:程序博客网 时间:2024/05/19 01:07

Spring的@PropertySource和@Value注解例子

Published:12 Feb 2015 Category:spring

在这篇文章中,我们会利用Spring的@PropertySource@Value两个注解从配置文件properties中读取值,以及如何从配置文件中的值转换为List对象。

创建Spring配置Class

@Configurable@ComponentScan(basePackages = "com.9leg.java.spring")@PropertySource(value = "classpath:spring/config.properties")public class AppConfigTest {        @Bean    public PropertySourcesPlaceholderConfigurer propertyConfigInDev() {        return new PropertySourcesPlaceholderConfigurer();    }    }

通过@PropertySource注解将properties配置文件中的值存储到Spring的Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。上面是读取一个配置文件,如果你想要读取多个配置文件,请看下面代码片段:

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

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

@PropertySources({@PropertySource("classpath:config.properties"),@PropertySource("classpath:db.properties")})public class AppConfig {//something}

另外在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属性来忽略找不到的文件

@Configuration@PropertySource(value="classpath:missing.properties", ignoreResourceNotFound=true)public class AppConfig {//something}
  @PropertySources({@PropertySource(value = "classpath:missing.properties", ignoreResourceNotFound=true),@PropertySource("classpath:config.properties")        })

最上面的AppConfigTest的配置代码等于如下的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>

创建properties配置文件

server.name=9leg,springserver.id=10,11,12server.jdbc=com.mysql.jdbc.Driver

创建一个简单的服务

@Component(value = "mockConfigTest")public class MockConfigTest {    @Value("#{'${server.name}'.split(',')}")    private List<String> servers;    @Value("#{'${server.id}'.split(',')}")    private List<Integer> serverId;        @Value("${server.host:127.0.0.1}")    private String noProKey;        @Autowired    private Environment environment;        public void readValues() {        System.out.println("Services Size : " + servers.size());        for(String s : servers)            System.out.println(s);        System.out.println("ServicesId Size : " + serverId.size());        for(Integer i : serverId)            System.out.println(i);        System.out.println("Server Host : " + noProKey);        String property = environment.getProperty("server.jdbc");        System.out.println("Server Jdbc : " + property);            }    public static void main(String[] args) {        AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AppConfigTest.class);        MockConfigTest mockConfigTest = (MockConfigTest) annotationConfigApplicationContext.getBean("mockConfigTest");        mockConfigTest.readValues();    }}

首先使用@Component注解声明,接着就是属性字段上的@Value注解,但在这里比较特殊,是通过split()方法,将配置文件中的9leg,spring分割后组成list对象。心细的同学可能注意到了server.host这个key并不存在配置文件中。是的,在这里使用的是默认值,即127.0.0.1,它的格式是这样的。

@value("${key:default}")private String var;

然后注入了Environment,可以通过getProperty(key)来获取配置文件中的值。运行main方法,来看下输出结果:

Services Size : 29legspringServicesId Size : 3101112Server Host : 127.0.0.1Server Jdbc : com.mysql.jdbc.Driver

最后要说一点,在main方法中请使用new AnnotationConfigApplicationContext(AppConfigTest.class)来代替new ClassPathXmlApplicationContext(“applicationContext.xml”)或者new FileSystemXmlApplicationContext(“src/main/resources/applicationContext.xml”)

原创文章转载请注明出处: Spring的@PropertySource和@Value注解例子

« 用maven骨架生成项目速度慢的问题Spring注解@Primary »
原创粉丝点击