@Value注解取值为NULL的几个可能原因与解决方案


在Spring MVC的架构中,如果希望在程序中直接引用properties中定义的配置值,通常是使用@Value注解的方式来获取:

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

但是取值的时候却可能会发现这个tagvalue的值为NULL,可能原因有:

1.使用了【static】修饰符或【final】修饰符修饰了tagValue。

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

这样导致了tagValue的值不可改变,注解无法注入配置值。

2.在类上没有加@Component注解(或者@service注解等)。

@Component // 必须要加上
class TestTagValue {
    @Value("${tagKey}")
    private String tagValue;
}

类上没有相应注解不能使该类被Spring容器统一管理,注解无法注入配置值。

3.使用new关键字新建了一个实例,而不是使用@Autowired注解。

@Component   
class TestTagValue{
    @Value("${tagKey}")
    private String tagValue;
}

@Service
class TestService {
    // 取得到tagValue值
    @AutoWired
    private TestTagValue testTagValue;
    
    // 取不到tagValue值
    TestTagValue testTagValue1 = new TestTagValue();
}

取不到的原因和2类似,在默认的情况下交由Spring容器管理的类是单例模式的,使用new关键字脱离了Spring容器的管理,成员变量值没有被注入。

 

"我走过万千世界,最后在心底留下一片荒原。"


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM