@Value注解取不到值的几种情况

spring的框架中,我们经常使用@Value注解来获取定义在application.properties的属性值,正常情况下是可以轻松的获取到值的,但是有几种特殊情况下是获取不到值的,在这记录下,以防止以后犯错误。正常获取的用法如下:

application.properties中定义一个属性值:

正常情况下在代码里面这样获取:

@Value("${ftpIP}")
private String ftpIP;

几种获取不到值的特殊情况如下

情况一:使用static或者final修饰了tagValue

@Value("${ftpIP}")
private static String ftpIP; 
@Value("${ftpUserName}")
private final String ftpUserName;

情况二:用该注解的类上面没有加注解,即不能被spring管理

public class FTPManagerService { 
 @Value("${ftpIP}")
 private static String ftpIP; 
}

情况三:类被new新建了实例,而没有使用@Autowired

public class FTPManagerService { 
 @Value("${ftpIP}")
 private static String ftpIP; 
} 
public class Test{
    /*错误用法*/
    FTPManagerService  f = new FTPManagerService ();
 
    /*正确用法*/
    @Autowired
    FTPManagerService  f2;
}

@Value取不到值的原因

在springboot中想获取配置文件中的值,一般的方法为

@Value("${tag}")
private String tagValue;

但是取值时,有时这个tagvalue为NULL,

可能原因有

1.类没有加上@Component(或者@service等)

@Component //遗漏
class TestValue{
    @Value("${tag}")
    private String tagValue;
}

2.类被new新建了实例,而没有使用@Autowired

@Component 
class TestValue{
    @Value("${tag}")
    private String tagValue;
} 
class Test{
    ...
    TestValue testValue = new TestValue()

正确方式

1.使用@Autowired注入

2.在controller层注值

以上为个人经验,希望能给大家一个参考,也希望大家多多支持悠悠之家。

点赞(53)

评论列表共有 0 条评论

立即
投稿
返回
顶部