美文网首页
SpringBoot: @Value

SpringBoot: @Value

作者: Taoyongpan | 来源:发表于2022-11-07 15:08 被阅读0次

使用规则

  • 不能修饰static:
  • 不能修饰final
  • 不能在没有注册的类中使用,例如util类
  • 不能使用new方式去创建对象,必须使用注入的方式

基本用法

  • 获取配置中key为topicSuffix的值
@Value("${topicSuffix}")
private String topicSuffix;
  • 将topicSuffix赋值为topic
@Value("#{topic}")
private String topicSuffix;
  • 如果获取不到配置则使用默认值topic
@Value("${topicSuffix:topic}")
private String topicSuffix;

修饰Static或者final类型返回null

因为静态变量是类的属性,并不属于对象的属性,而Spring是基于对象的属性进行依赖注入的。所以用@Value注解注入静态变量是失败的。(约定大于配置)

  • 修饰static参数实践
@Component
public class StaticTest {

    @Value("${static.test:test}")
    public String test;

    public static String testStatic;

    /**
     * 方法1
     * @return
     */
    public String getTestStatic(){
        testStatic = this.test;
        return testStatic;
    }

    /**
     * 方法2
     * @param testStatic
     */
    @Value("${static.test:test}")
    public void setTestStatic(String testStatic){
        StaticTest.testStatic = testStatic;
    }
}

相关文章

网友评论

      本文标题:SpringBoot: @Value

      本文链接:https://www.haomeiwen.com/subject/iovwtdtx.html