@Value 注解獲取為空,@PostConstruct注解使用


老是忘記,就做個記錄

@Value

  • @Value不能和 staticfinal 搭配使用
@Value("${XXX.XXX}")
public static String xxx;  // 錯誤
@Value("${XXX.AAA}")
public finalString xxx; // 錯誤
  • 類沒有加上@Component(或者@service等)
  • 類被new新建了實例,而沒有使用@Autowired

@PostConstruct

這個不是spring的注解,是java自己的
@PostConstruct該注解被用來修飾一個非靜態的void()方法。被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之后執行,init()方法之前執行。
舉例:

    @Autowired
    private Environment env;

    private String ecUrl;

    @PostConstruct
    public void init(){
        ecUrl = env.getProperty("ec.url");
    }


免責聲明!

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



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