SpringBoot: @Value

使用规则

  • 不能修饰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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容