buguge - Keep it simple,stupid

知识就是力量,但更重要的,是运用知识的能力why buguge?

导航

Spring @Value注解 and Spring Boot @ConfigurationProperties注解

 

一、Spring的@Value

Spring支持在XML配置文件和注解中使用Spring  EL(Spring 表达式语言),Spring EL类似于JSP的EL表达式语言。

在Spring开发中经常涉及调用各种资源的情况,包含普通文件、网址、配置文件、系统环境变量等,我们可以使用Spring的表达式语言实现资源的注入。

 

程序代码里,Spring主要在@Value注解的参数中使用EL表达式。

  • 注入普通字符串
  • 注入操作系统属性
  • 注入表达式运算结果
  • 注入其他Bean的属性
  • 注入文件内容
  • 注入网址内容
  • 注入属性文件(注意:用的是$符号)
import org.springframework.core.io.Resource;
import org.springframework.core.env.Environment;
import org.apache.commons.io.IOUtils;

@Component
public class ELConfig {
  
    @Value("${book.name}")// 注入配置文件【注意是$符号】  
    private String bookName;  

    @Value("注入普通字符串")// 注入普通字符串  
    private String normal;  
      
    @Value("#{systemProperties['os.name']}")// 注入操作系统属性  
    private String osName;  
      
    @Value("#{T(java.lang.Math).random() * 100.0 }")// 注入表达式结果  
    private double randomNumber;   
 
    @Value("#{payOrderQueryController.payCenterFacade}")// 注入其他Bean属性
    private IPayCenterFacade fromAnother;
      
    @Value("classpath:test.txt")// 注入文件资源  
    private Resource testFile;  
      
    @Value("https://www.baidu.com")// 注入网址资源  
    private Resource testUrl;  
      
    @Autowired// Properties可以从Environment获得  
    private Environment environment;  
  
    @Override  
    public String toString() {  
        try {  
            return "ELConfig [normal=" + normal   
                    + ", osName=" + osName   //os.name,如Windows 8.1
                    + ", randomNumber=" + randomNumber   //值如97.53293482705482
                    + ", fromAnother=" + fromAnother   //别的bean的成员属性
                    + ", testFile=" + IOUtils.toString(testFile.getInputStream())   //输出文件里的内容
                    + ", testUrl=" + IOUtils.toString(testUrl.getInputStream())   //输出网页的html
                    + ", bookName=" + bookName  //配置的值
                    + ", environment=" + environment.getProperty("book.name") + "]";  
        } catch (IOException e) {  
            e.printStackTrace();  
            return null;  
        }  
    }        
}  

 

小贴士

利用@Value注入property值时,如果property不存在(未配置),则会导致应用程序无法启动。BeanCreationException异常: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'productCode' in value "${productCode}"

@RestController
public class DefaultController {

    @Value("${productCode}")
    private int productCode;

可以为枚举类型属性注入property,这是按Enum#name来匹配的,所以property的值需要配置成枚举的name。

    @Value("${season:SPRING}")
    private SeasonsEnum season;

 

 小测试,考考你

下面这种,当property不存在时,smsSignature值是什么?----答:空字符串

    @Value("${platform.sms.signature:}") // 短信签名
    private String smsSignature;

下面这种,当property不存在时,smsSignature值是什么?----答:字符串null

    @Value("${platform.sms.signature:null}") // 短信签名
    private String smsSignature;

下面这种,当property不存在时,productCode值是什么?----答:112

    @Value("${productCode:112}")
    private int productCode;

下面这种呢?----答:会导致应用程序无法启动。异常: org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "null"

    @Value("${productCode:null}") 
    private Integer productCode;

 

二、Spring Boot的@ConfigurationProperties

先看下面的@Value注解:

    @Value("${book.name}")
    private String bookName;
    @Value("${book.author}")
    private String bookAuthor;

 上面这种使用@Value注入每个配置在实际项目中会显得格外麻烦,因为我们的配置通常会是许多个,就要使用@Value注入很多次。

Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean关联,从而实现类型安全的配置。

@Component
@ConfigurationProperties(prefix = "book")
public class Book {

    private String name;
    private String author;
    private int age;
    
    //getter.. setter..
}

 application.yml配置:

book:
  name: 一个人的朝圣
  author: 蕾秋·乔伊斯
  age: 35

 

@ConfigurationProperties有两个属性

  • prefix:指定properties的配置的前缀
  • locations:指定properties文件的位置

 

posted on 2018-03-30 20:34  buguge  阅读(960)  评论(0编辑  收藏  举报