zoukankan      html  css  js  c++  java
  • @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容器的管理,成员变量值没有被注入。

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

    你要去做一个大人,不要回头,不要难过。
  • 相关阅读:
    SpringMVC+Huploadify 实现文件上传下载
    删除代码中的注释
    shiro框架学习(二)
    shiro框架学习(三)
    shiro框架学习(一)
    数据库操作导入导出以及加快查询速度
    判断字符串中是否是数字
    分数判断
    异常处理的课后
    多态的课后总结
  • 原文地址:https://www.cnblogs.com/yanggb/p/14386141.html
Copyright © 2011-2022 走看看