Value注解获取值一直为Null

@Value("${jwt.tokenHeader}")
    private String tokenHeader;

常见的错误解决办法如下:

1、使用static或final修饰了tagValue,如下:

private static String tagValue; //错误
private final String tagValue; //错误


2、类没有加上@Component(或者@service等)

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

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

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

class Test{
TestValue testValue = new TestValue()

这个testValue中肯定是取不到值的,必须使用@Autowired:

class Test{
@AutoWired
TestValue testValue
}

最后一个原因归根结底还是因为类没有放进spring 容器中,在类上面加@Componet注解项目启动报错,最后找到原因:

在于new 了这个类之后少了@bean注解,加上之后就能获取到yml中配置的值:

 @Bean //缺失
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }
唯有热爱方能抵御岁月漫长。
原文地址:https://www.cnblogs.com/syq816/p/14476699.html