Spring使用@Value值注入不成功问题

使用@Value注解获取配置文件中的值不成功

先查看这个注解导入的对不对

import org.springframework.beans.factory.annotation.Value;

再查看里面的变量是否是${} 这种形式取的值

@Value("${example.useTable}")
private boolean useTable;

// yml中配置
example:
  useTable: true

再查看注入此属性的类是否加了@Component注解

没加注解就代表没有注册到spring容器中,自然也是没办法注入值的

@Component
public class Example {

    @Value("${example.useTable}")
    private boolean useTable;
}

【最关键】查看用这个类的地方

是否是从spring中获取的,如果是从spring中拿的,值是肯定有的,如果是手动new 出来的,肯定不会注入成功的!


Spring使用@Value值注入不成功问题
https://www.powercheng.fun/articles/2edfbfe8/
作者
powercheng
发布于
2021年11月7日
许可协议