Spring @Value 注解

265 阅读1分钟

在 Spring 中看到使用 @Value 时,有的使用【$】,也有使用【#】的,那么他俩有什么区别呢?

用途区别

  • 【$】主要获取的是配置文件 application.yml /application.proterties 中的配置信息。
  • 【#】主要获取的是对象中的方法或者属性值,也可以是表达式返回的值。 获取对象内属性的值,需要属性有 set、get 方法,例如下方示例 TestModel 的 name。
  • 【#】还可以和【】结合使用,可以对【】结合使用,可以对 【】引用的变量进行简单的的逻辑处理。

示例

  • application.yml 配置
config:
  version: v1.0.0
  test: test
  • Config 类
@ConfigurationProperties("config")
@Component
public class Config {
    private String version;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}
  • TestModel 类
@Component
public class TestModel {
    private String name = "testModel";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String resetName(){
        return this.name+"+reset";
    }
}
  • 使用类
@RestController
@RequestMapping("/testApi")
public class TestController {

    @Value("${config.test}")
    private String test;

    @Value("#{config.version}")
    private String version;

    @Value("#{testModel.name}")
    private String name;

    @Value("#{testModel.resetName()}")
    private String resetName;

    @Value("#{T(java.lang.Math).random()* 100.0}")
    private double randomNum;

    @Value("#{'${config.test}'+'ddd'}")
    private String mergeAdd;

    @Value("#{'${config.test}'.substring(2)}")
    private String mergeSub;

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public void test(){
        System.out.println(test);// test
        System.out.println(version);// v1.0.0
        System.out.println(name);// testModel
        System.out.println(resetName);// testModel+reset
        System.out.println(randomNum);// 46.709772758997524
        System.out.println(mergeAdd);// testddd
        System.out.println(mergeSub);// st
    }
}

总结

Spring 相关还有很多知识点,例如:IOC 容器、AOP、数据访问、Web开发、消息、测试等。它是个博大精深的东西,想要很熟练的使用Spring ,还有很长的路要走(Spring MVC、Spring Boot、Spring Cloud)。继续努力💪。