Spring @Value注释技巧

Spring框架提供@值中的注释org.springframework.beans.factory.annotation包。 此注释在我们的应用程序中的各个级别上使用,在字段级别上用于表达式驱动的依赖项注入,其中,可以将值注入到类中的变量中,或者在表示默认值表达式的方法或构造函数的参数级别中 作为主要论点。 它也用于动态解析处理程序方法参数,例如在Spring MVC中。

@值注释可以在带有注释的类中使用@组态,@零件和其他定型注释,例如@Controller,@服务等等的实际处理@值注释由BeanPostProcessor执行,因此@值不能在BeanPostProcessor类类型中使用。

@值注释使用属性占位符语法$ {...}和Spring Expression Language,SpEL,语法#{$ ...}制定表达方式。$ {...}是属性占位符语法,而#{$ ...}是SpEL语法。#{$ ...}语法还可以处理属性占位符等等。

In this write-up, I will discuss some tricks in using @Value annotation in a sample Spring Boot application. Let go to https://start.spring.io/ to generate and bootstrap our project.

选择Maven Project,Java作为语言,为您的项目指定组名和工件ID。 选择Spring Web作为我们项目的唯一依赖项。

1%2ArkM6r6vHe6LQGcPRQCJnGQ.png

点击“生成”按钮,将自举项目下载为zip文件。 解压缩文件,并使用首选的IDE作为Maven项目打开它,以下载所有必需的依赖项。

1%2A4aaXIKuCYbqB5pUsAeyYQQ.png

创建一个新程序包,将其命名为“ controller”,并创建一个新类,名为ValueController.java。 确保其中包含以下内容

1%2AhM9kmAThtlrQeB9mZ58OnQ.png

在这里,我已经用@RestController为构造型Controller的子级注释了该类,以便值注释可以注入并正常工作。

1. @Value Placeholder Syntax @Value("")

package com.habeebcycle.springvalueannotation.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ValueController {

    @Value("Hello World")
    private String greetingMessage;

    @GetMapping("")
    public String sendGreeting(){
        return greetingMessage;
    }
}

The value annotation is used to hold the value for the variable greetingMessage. When the project is run and the endpoint http://localhost:8080 is hit, the word Hello World is displayed on the browser. This shows that the @Value annotation works very well with class variables to inject the default value at runtime. As it works with String data type, it also works for other primitives and wrapper types like int, double, boolean, Integer, Double and Boolean as shown below:

@Value("1.234")
private double doubleValue; //could be Double

@Value("1234")
private Integer intValue; //could be int

@Value("true")
private boolean boolValue; //could be Boolean

@Value("2000")
private long longValue;

2. @Value Property Placeholder Syntax @Value("${...}")

大多数spring应用程序都有一个属性文件,该文件用于在应用程序中配置某些值或属性。 SpringApplication从中加载属性application.properties文件放在类路径中,然后将它们添加到Spring Environment中。 在上面的示例中,spring boot初始化程序已经在src / main / resource文件夹下的应用程序中自举了application.properties文件。 让我们创建一些属性,然后使用@值注解。

#application.properties
greeting.message=Hello World!

我们可以用@Value(“ $ {...属性名称}”)批注以访问Java类中的上述属性,如下所示:

ackage com.habeebcycle.springvalueannotation.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ValueController {

    @Value("${greeting.message}") 
    private String greetingMessage;

    @GetMapping("")
    public String sendGreeting(){
        return greetingMessage;
    }
}

Hitting the endpoint http://127.0.0.1:8080 will display the variable greetingMessage as Hello World! on the browser. The property value is injected at runtime from the property file to the variable.

如果属性名称不存在于application.properties文件,应用程序将引发错误,如下所示:

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-02-29 21:54:43.953 ERROR 2996 --- [           main] o.s.boot.SpringApplication               : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'valueController': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'greeting.message' in value "${greeting.message}"

可以为注释提供一个默认值,如果属性名称在@值注释不存在application.properties文件。 实现如下所示:

package com.habeebcycle.springvalueannotation.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ValueController {

    @Value("${greeting.message:Greeting not found!}")
    private String greetingMessage;

    @GetMapping("")
    public String sendGreeting(){
        return greetingMessage;
    }
}

冒号:放在属性名称的前面,并且默认值提供给注释。 如果未在属性中找到属性名称,这将指示注释使用为其提供的默认值。application.properties文件。 提供有关冒号所在位置的默认值时应谨慎:被放置。 属性名称和冒号之间是否有空格:如图所示

@Value("${greeting.message :Greeting not found!}")
private String greetingMessage;

即使属性名称存在于属性文件中,也将始终使用提供的默认值。 因此,不应在冒号之前插入空格: as it might cause unexpected behaviour. This also applies to other primitives and wrapper types like int, double, boolean, Integer, Double and Boolean as shown below:

#application.properties

my.int.value=20
my.double.value=3.142
my.boolean.value=true

//In the Java file

@Value("${my.int.value:0}")
private int intValue; //injects 20 at runtime

@Value("${my.double.value: 0.0}")
private double doubleValue; //injects 3.142 at runtime

//This takes the default value provided despite having the property 
//name in the properties file.
@Value("${my.boolean.value :false}")
private boolean boolValue; //injects false because of space

//Property name not found in the properties file
@Value("${my.long.value:300}")
private long longValue; //injects 300 at runtime

3. @Value Property Placeholder Syntax @Value("${...}") with List of values

@Value(“ $ {...}”)可用于在运行时从属性文件注入列表值。 考虑下面的属性文件:

#application.properties
my.weekdays=Mon,Tue,Wed,Thu,Fri

并在Java文件中

@Value("${my.weekdays}")
private List<String> strList; // injects [Mon, Tue, Wed, Thu, Fri]

//Providing default value
@Value("${my.weekends:Sat,Sun,Fri}")
private List<String> strList2; // injects [Sat, Sun, Fri]

4. @Value Spring Expression Language Syntax @Value("#{${...}}") with Map (key-value pair)

@Value(“#{$ {...}}”)可用于在运行时从属性文件注入映射(键-值)对。 以下示例显示了如何执行此操作:

#application.properties
database.values={url:'http://127.0.0.1:3306/', db:'mySql', username:'root', password:'root'}

我们可以使用SpEL如下注入数据库值属性。

package com.habeebcycle.springvalueannotation.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class ValueController {

    @Value("#{${database.values}}")
    private Map<String, String> dbValues;

    @GetMapping("")
    public Map getDBProps(){
        return dbValues;
    }
}

Hitting endpoint http://localhost:8080 will return the following output

{
  "url": "http://127.0.0.1:3306/",
  "db": "mySql",
  "username": "root",
  "password": "root"
}

要在属性文件中找不到属性名称的情况下使用默认值。

@Value("#{${database.values: {url: 'http://127.0.0.1:3308/', db: 'mySql', username: 'root', password: ''}}}")
private Map<String, String> dbValues;

When database.values property is not defined in the properties file, the default map {url:'http://127.0.0.1:3308/', db:'mySql', username:'root', password:''} will be injected to the variable dbValues at runtime.

5. @Value Construction Injection with @Value("${...}")

@值可以与构造函数参数一起使用,然后在构造函数注入中,Spring将注入由指定的值@值注解。 假设我们在属性文件中具有以下属性。

#application.properties

company.name= Scopesuite Pty ltd
#company.location= Sydney

我们可以用@值构造期间的注释如下

package com.habeebcycle.springvalueannotation.service;
import org.springframework.stereotype.Service;
@Service
public class CompanyService {
   private String compName;
   private String location;

   public CompanyService(@Value("${company.name}") String compName,
    @Value("${company.location:Washington}") String location){

       this.compName = compName;
       this.location = location;
   }
   ------
}

在上述构造函数中,将使用属性文件中的值注入第一个参数。 如果找不到第二个参数的属性键,则将注入默认值。

from: https://dev.to//habeebcycle/spring-value-annotation-tricks-1a80

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值