@Value取值為NULL的解決方案


在spring mvc架構中,如果希望在程序中直接使用properties中定義的配置值,通常使用一下方式來獲取:

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

但是取值時,有時這個tagvalue為NULL,可能原因有:

  • 使用static或final修飾了tagValue,如下:
    private static String tagValue;  //錯誤
    private final String tagValue;    //錯誤
   
   
  
  
          
  • 類沒有加上@Component(或者@service等)
    @Component   //遺漏
    class TestValue{
         @Value("${tag}")
         private String tagValue;
    }
   
   
  
  
          
  • 類被new新建了實例,而沒有使用@Autowired
    @Component   
    class TestValue{
         @Value("${tag}")
         private String tagValue;
    }

    class Test{
        ...
        TestValue testValue = new TestValue()
    }
   
   
  
  
          

這個testValue中肯定是取不到值的,必須使用@Autowired:

class Test{
        @AutoWired
        TestValue testValue
    }
   
   
  
  
          
原文地址:https://blog.csdn.net/zzmlake/article/details/54946346


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM