解決@Autowired注入空指針問題(利用Bean的生命周期)
今天做項目的時候遇到一個問題,需要將線程池的參數(shù)抽取到y(tǒng)ml文件里進行設置。這不是so easy嗎?
我就寫出了下面這樣的代碼進行抽取
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @author BestQiang */ @Component @ConfigurationProperties(prefix = "thread-pool") public class ThreadPool { private int corePoolSize; private int maximumPoolSize; private long keepAliveTime; private int capacity; public int getCorePoolSize() { return corePoolSize; } public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; } public int getMaximumPoolSize() { return maximumPoolSize; } public void setMaximumPoolSize(int maximumPoolSize) { this.maximumPoolSize = maximumPoolSize; } public long getKeepAliveTime() { return keepAliveTime; } public void setKeepAliveTime(long keepAliveTime) { this.keepAliveTime = keepAliveTime; } public int getCapacity() { return capacity; } public void setCapacity(int capacity) { this.capacity = capacity; } }
package cn.bestqiang.util; import cn.bestqiang.pojo.ThreadPool; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.concurrent.*; /** * @author Yaqiang Chen */ @Component public class MyThreadUtils { @Autowired ThreadPool threadPool1; private ExecutorService threadPool = new ThreadPoolExecutor( threadPool1.getCorePoolSize(), threadPool1.getMaximumPoolSize(), threadPool1.getKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(threadPool1.getCapacity()), namedThreadFactory, new ThreadPoolExecutor.DiscardPolicy() );; private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("pool-%d").build(); public void execute(Runnable runnable){ threadPool.submit(runnable); } }
在yml文件的配置如下:
thread-pool: ? core-pool-size: 5 ? maximum-pool-size: 20 ? keep-alive-time: 1 ? capacity: 1024
本想應該毫無問題,但是,報錯了:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myThreadUtils' defined in fileXXXXXXXXXX(省略)Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [cn.itcast.util.MyThreadUtils]: Constructor threw exception; nested exception is java.lang.NullPointerExceptionCaused by: java.lang.NullPointerException: null
空指針異常?檢查好幾遍配置沒錯。因為公司開發(fā)環(huán)境沒法上網(wǎng),只好拖到下班google了一下,結(jié)合我比較深厚的基礎(自戀一下),
問題輕松解決
這就是答案。上面說所有的Spring的@Autowired注解都在構造函數(shù)之后,而如果一個對象像下面代碼一樣聲明(private XXX = new XXX() 直接在類中聲明)的話,成員變量是在構造函數(shù)之前進行初始化的,甚至可以作為構造函數(shù)的參數(shù)。
即 成員變量初始化 -> Constructor -> @Autowired
所以,在這個時候如果成員變量初始化時調(diào)用了利用@Autowired注解初始化的對象時,必然會報空指針異常的啊。
真相大白了。如果解決呢?那就讓上面我寫的代碼的成員變量threadPool在@Autowired之后執(zhí)行就好了。
要想解決這個問題,首先要知道@Autowired的原理:
AutowiredAnnotationBeanPostProcessor 這個類
其實看到這個繼承結(jié)構,我心中已經(jīng)有解決辦法了。具體詳細為什么,等997的工作結(jié)束(無奈)我會在后續(xù)博客里將Spring的注解配置詳細的捋一遍,到時候會講到Bean的生命周期的。
繼承的BeanFactoryAware是在屬性賦值完成,執(zhí)行構造方法后,postProcessBeforeInitialization才執(zhí)行,而且,是在其他生命周期之前,而@Autowired注解就是依靠這個原理進行的自動注入。想要解決這個問題很簡單,就是把要賦值的成員變量放到其他生命周期中就可以。
下面介紹其中兩種辦法
第一種JSR250的@PostConstruct
@PostConstruct public void init() { // 這里放要執(zhí)行的賦值 }
第二種是Spring的InitializingBean(定義初始化邏輯)
繼承接口實現(xiàn)方法即可,這種直接放上完整用法
/** * @author Yaqiang Chen */ @Component public class MyThreadUtils implements InitializingBean { @Autowired ThreadPool threadPool1; private ExecutorService threadPool; private ThreadFactory namedThreadFactory = new ThreadFactoryBuilder() .setNameFormat("pool-%d").build(); public void execute(Runnable runnable){ threadPool.submit(runnable); } @Override public void afterPropertiesSet() throws Exception { threadPool = new ThreadPoolExecutor( threadPool1.getCorePoolSize(), threadPool1.getMaximumPoolSize(), threadPool1.getKeepAliveTime(), TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(threadPool1.getCapacity()), namedThreadFactory, new ThreadPoolExecutor.DiscardPolicy() ); } }
設置完成后,問題解決!
相關文章
SpringBoot中配置Web靜態(tài)資源路徑的方法
這篇文章主要介紹了SpringBoot中配置Web靜態(tài)資源路徑的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09JAVA對象JSON數(shù)據(jù)互相轉(zhuǎn)換的四種常見情況
這篇文章主要介紹了JAVA對象JSON數(shù)據(jù)互相轉(zhuǎn)換的四種常見情況,需要的朋友可以參考下2014-04-04