前言

译文链接:http://websystique.com/spring/spring-propertysource-value-annotations-example/

本篇文章将展示如何通过@PropertySource@Value注解从配置文件中读取属性值。

同样,我们也会讨论Spring的Environment接口,还会看到使用XML配置和使用注解的对比。

Spring的@PropertySource注解主要是让Spring的Environment接口读取属性配置文件用的,这个注解是标识在@Configuration配置类上的。

Spring的@Value注解可以用在字段和方法上。通常用于从属性配置文件中读取属性值,也可以设置默认值。接下来就让我么看下完整的例子吧。

涉及的技术及开发工具

  • Spring 4.0.6.RELEASE
  • Maven 3
  • JDK 1.6
  • Eclipse JUNO Service Release 2

工程结构目录

步骤一:往pom.xml中添加依赖

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4.  
  5. <groupId>com.websystique.spring</groupId>
  6. <artifactId>Spring4PropertySourceExample</artifactId>
  7. <version>1.0.0</version>
  8. <packaging>jar</packaging>
  9.  
  10. <name>Spring4PropertySourceExample</name>
  11.  
  12. <properties>
  13. <springframework.version>4.0.6.RELEASE</springframework.version>
  14. </properties>
  15.  
  16. <dependencies>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-core</artifactId>
  20. <version>${springframework.version}</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>org.springframework</groupId>
  24. <artifactId>spring-context</artifactId>
  25. <version>${springframework.version}</version>
  26. </dependency>
  27. </dependencies>
  28. <build>
  29. <pluginManagement>
  30. <plugins>
  31. <plugin>
  32. <groupId>org.apache.maven.plugins</groupId>
  33. <artifactId>maven-compiler-plugin</artifactId>
  34. <version>3.2</version>
  35. <configuration>
  36. <source>1.6</source>
  37. <target>1.6</target>
  38. </configuration>
  39. </plugin>
  40. </plugins>
  41. </pluginManagement>
  42. </build>
  43.  
  44. </project>

步骤二:创建Spring配置类

Spring配置类是指用@Configuration注解标注的类,这些类包含了用@Bean标注的方法。这些被@Bean标注的方法可以生产bean并交由spring容器管理。

  1. package com.websystique.spring.configuration;
  2.  
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.ComponentScan;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.context.annotation.PropertySource;
  7. import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
  8.  
  9. @Configuration
  10. @ComponentScan(basePackages = "com.websystique.spring")
  11. @PropertySource(value = { "classpath:application.properties" })
  12. public class AppConfig {
  13.  
  14. /*
  15. * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations.
  16. * Remove this bean if you are not using @Value annotations for injecting properties.
  17. */
  18. @Bean
  19. public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  20. return new PropertySourcesPlaceholderConfigurer();
  21. }
  22. }

@PropertySource(value = { “classpath:application.properties” })注解可以让在application.properties文件中定义的属性对Spring Envirronment bean可用,Environment接口提供了getter方法读取单独的属性值。

注意PropertySourcesPlaceholderConfigurer这个bean,这个bean主要用于解决@value中使用的${…}占位符。假如你不使用${…}占位符的话,可以不使用这个bean。

以上的配置使用XML替代的话,如下:

app-config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  7.  
  8. <context:component-scan base-package="com.websystique.spring"/>
  9.  
  10. <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
  11. <property name="ignoreUnresolvablePlaceholders" value="true"/>
  12. <property name="locations">
  13. <list>
  14. <value>classpath:application.properties</value>
  15. </list>
  16. </property>
  17. </bean>
  18. </beans>

步骤三:创建配置文件

  1. jdbc.driverClassName = com.mysql.jdbc.Driver
  2. jdbc.url = jdbc:mysql://localhost:3306/websystique
  3. jdbc.username = myuser
  4. jdbc.password = mypassword
  5. hibernate.dialect = org.hibernate.dialect.MySQLDialect
  6. hibernate.show_sql = false
  7. hibernate.format_sql = false
  8. sourceLocation = /dev/input

我们将会在service类里使用上面提到的配置方式读取这个配置文件

步骤四:创建服务类

  1. package com.websystique.spring.service;
  2.  
  3. public interface FileService {
  4.  
  5. void readValues();
  6. }
  1. package com.websystique.spring.service;
  2.  
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.beans.factory.annotation.Value;
  5. import org.springframework.core.env.Environment;
  6. import org.springframework.stereotype.Service;
  7.  
  8. @Service("fileService")
  9. public class FileServiceImpl implements FileService {
  10.  
  11. @Value("${sourceLocation:c:/temp/input}")
  12. private String source;
  13.  
  14. @Value("${destinationLocation:c:/temp/output}")
  15. private String destination;
  16.  
  17. @Autowired
  18. private Environment environment;
  19.  
  20. public void readValues() {
  21. System.out.println("Getting property via Spring Environment :"
  22. + environment.getProperty("jdbc.driverClassName"));
  23.  
  24. System.out.println("Source Location : " + source);
  25. System.out.println("Destination Location : " + destination);
  26.  
  27. }
  28.  
  29. }

这里首先要注意的是Environment bean被Spring自动注入。另外,由于配置了@PropertySoruce注解,Environment bean可以访问指定配置文件里定义的所有属性值。你可以使用getProperty方法得到指定值。

另外一点值得注意的是@Value注解,基本格式如下:

  1. @value("${key:default")
  2. private String var;

以上声明指导spring根据key去属性配置文件查找value,如果没找到,则使用default作为默认值。

注意以上的${…}占位符只有当注册了PropertySourcesPlaceholderConfigurer bean后才能被解析,否则@Value注解会一直将默认值赋值给var。

步骤五:创建Main方法运行程序

  1. package com.websystique.spring;
  2.  
  3. import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  4. import org.springframework.context.support.AbstractApplicationContext;
  5.  
  6. import com.websystique.spring.configuration.AppConfig;
  7. import com.websystique.spring.service.FileService;
  8.  
  9. public class AppMain {
  10.  
  11. public static void main(String args[]){
  12. AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
  13. FileService service = (FileService) context.getBean("fileService");
  14.  
  15. service.readValues();
  16. context.close();
  17. }
  18.  
  19. }

运行以上程序,得到如下结果:

Getting property via Spring Environment :com.mysql.jdbc.Driver
Source Location : /dev/input
Destination Location : c:/temp/output
由于destinationLocation属性在application.properties文件中没定义,所以使用默认值。
最后,若使用XML配置,请将
AbstractApplicationContext  context = new AnnotationConfigApplicationContext(AppConfig.class);
替换为
AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-config.xml");
即可,
会得到相同的输出结果。

工程源码

http://websystique.com/?smd_process_download=1&download_id=796

【译】Spring 4 @PropertySource和@Value注解示例的更多相关文章

  1. Spring学习(三)——@PropertySource,@ImportResource,@Bean注解

    @PropertySource注解是将配置文件中 的值赋值给POJO 项目结构如下 一.创建一个Person.Java文件: import org.springframework.boot.conte ...

  2. [译]Spring构建微服务

    此文为译文,原文地址 介绍 本文通过一个使用Spring.Spring Boot和Spring Cloud的小例子来说明如何构建微服务系统. 我们可以通过数个微服务组合成一个大型系统. 我们可以想象下 ...

  3. 深入学习Spring框架(二)- 注解配置

    1.为什么要学习Spring的注解配置? 基于注解配置的方式也已经逐渐代替xml.所以我们必须要掌握使用注解的方式配置Spring. 关于实际的开发中到底使用xml还是注解,每家公司有着不同的使用习惯 ...

  4. 循序渐进之Spring AOP(6) - 使用@Aspect注解

    前面几节的示例看起来让人沮丧,要记忆如此多的接口.类和继承关系,做各种复杂的配置.好在这些只是一种相对过时的实现方式,现在只需要使用@Aspect注解及表达式就可以轻松的使用POJO来定义切面,设计精 ...

  5. Spring的bean管理(注解)

    前端时间总是用配置文件  内容太多 下面认识一下注解 注解是什么? 1代码里面的特殊标记,使用注解可以完成功能 2注解写法@XXX 3使用注解可以少些很多配置文件 Spring注解开发准备 注解创建准 ...

  6. J2EE进阶(十三)Spring MVC常用的那些注解

    Spring MVC常用的那些注解 前言 Spring从2.5版本开始在编程中引入注解,用户可以使用@RequestMapping, @RequestParam,@ModelAttribute等等这样 ...

  7. Spring和SpringMVC的常用注解

    Spring的部分: 使用注解之前要开启自动扫描功能 其中base-package为需要扫描的包(含子包). <context:component-scan base-package=" ...

  8. (转)Spring的bean管理(注解方式)

    http://blog.csdn.net/yerenyuan_pku/article/details/69663779 Spring的bean管理(注解方式) 注解:代码中的特殊标记,注解可以使用在类 ...

  9. Spring自动装配----注解装配----Spring自带的@Autowired注解

    Spring自动装配----注解装配----Spring自带的@Autowired注解 父类 package cn.ychx; public interface Person { public voi ...

随机推荐

  1. 锤子OneStep及BigBang使用体验

    令人期待的Smartisan OS v3.1.2终于推送了,第一时间下载了更新.几乎花了半个小时才升级完毕,捧着还热乎的手机,赶忙体验一下传说中的两大杀器:OneStep以及BigBang. 先说On ...

  2. Thinking in Unity3D:基于物理着色(PBS)的材质系统

    关于<Thinking in Unity3D> 笔者在研究和使用Unity3D的过程中,获得了一些Unity3D方面的信息,同时也感叹Unity3D设计之精妙.不得不说,笔者最近几年的引擎 ...

  3. Go语言实战 - revel框架教程之CSRF(跨站请求伪造)保护

    CSRF是什么?请看这篇博文“浅谈CSRF攻击方式”,说的非常清楚. 现在做网站敢不防CSRF的我猜只有两种情况,一是没什么人访问,二是局域网应用.山坡网之前属于第一种情况,哈哈,所以至今没什么问题. ...

  4. 背后的故事之 - 快乐的Lambda表达式(二)

    快乐的Lambda表达式 上一篇 背后的故事之 - 快乐的Lambda表达式(一)我们由浅入深的分析了一下Lambda表达式.知道了它和委托以及普通方法的区别,并且通过测试对比他们之间的性能,然后我们 ...

  5. Docker私有仓库搭建

    # 环境 系统 Linux 3.10.0-123.9.3.el7.x86_64 CentOS 7.0.1406 (Core) Docker 1.12.0, build 8eab29e 1.获取镜像 私 ...

  6. 断电不断网——Linux的screen

    title: 断电不断网--Linux的screen author:青南 date: 2015-01-01 20:20:23 categories: [Linux] tags: [linux,scre ...

  7. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(16)-权限管理系统-漂亮的验证码

    系列目录 我们上一节建了数据库的表,但我发现很多东西还未完善起来,比如验证码,我们先做好验证码吧,验证码我们再熟悉不过了,为了防止恶意的登录,我们必须在登录页面加入验证码,下面我将分享一个验证码,这个 ...

  8. .NET平台开源项目速览(1)SharpConfig配置文件读写组件

    在.NET平台日常开发中,读取配置文件是一个很常见的需求.以前都是使用System.Configuration.ConfigurationSettings来操作,这个说实话,搞起来比较费劲.不知道大家 ...

  9. K近邻法(KNN)原理小结

    K近邻法(k-nearst neighbors,KNN)是一种很基本的机器学习方法了,在我们平常的生活中也会不自主的应用.比如,我们判断一个人的人品,只需要观察他来往最密切的几个人的人品好坏就可以得出 ...

  10. 【Big Data】HADOOP集群的配置(二)

    Hadoop集群的配置(二) 摘要: hadoop集群配置系列文档,是笔者在实验室真机环境实验后整理而得.以便随后工作所需,做以知识整理,另则与博客园朋友分享实验成果,因为笔者在学习初期,也遇到不少问 ...