程序使用到一個場景:我有一個execute.class。但是調用它之前需要去數據庫獲取一些必要的配置項,且無需多次查詢(即初始化class前調用一次即可)。后來發現這個注解,驚為**
注解說明:@PostConstruct該注解被用來修飾一個非靜態的void()方法。被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之后執行,init()方法之前執行。
代碼:
package com.example.demo.controller.taskexecute; import com.example.demo.service.ConfigService; import org.apache.commons.lang.StringUtils; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @Author Ctrl` * @Since 2019/10/31. */ @Component public class SpiderExecute { public static SpiderExecute spiderExecute; private final Logger log = LoggerFactory.getLogger(SpiderExecute.class); @Autowired ConfigService configService; /** * 初始化當前類方法 * @PostConstruct 便於直接加載注入類 */ @PostConstruct public void init() { spiderExecute = this; log.info("execute init."); spiderExecute.configService = this.configService; }
因為該類是執行類,沒有使用@Controller注解。這樣@Autowired就無法自動注入service了。直接調用會拋NullPointException異常.
於是使用該注解解決了問題。