解決@Autowired註入空指針問題(利用Bean的生命周期)

今天做項目的時候遇到一個問題,需要將線程池的參數抽取到yml文件裡進行設置。這不是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

空指針異常?檢查好幾遍配置沒錯。因為公司開發環境沒法上網,隻好拖到下班google瞭一下,結合我比較深厚的基礎(自戀一下),

問題輕松解決

這就是答案。上面說所有的Spring的@Autowired註解都在構造函數之後,而如果一個對象像下面代碼一樣聲明(private XXX = new XXX() 直接在類中聲明)的話,成員變量是在構造函數之前進行初始化的,甚至可以作為構造函數的參數。

即 成員變量初始化 -> Constructor -> @Autowired

所以,在這個時候如果成員變量初始化時調用瞭利用@Autowired註解初始化的對象時,必然會報空指針異常的啊。

真相大白瞭。如果解決呢?那就讓上面我寫的代碼的成員變量threadPool在@Autowired之後執行就好瞭。

要想解決這個問題,首先要知道@Autowired的原理:

AutowiredAnnotationBeanPostProcessor 這個類

其實看到這個繼承結構,我心中已經有解決辦法瞭。具體詳細為什麼,等997的工作結束(無奈)我會在後續博客裡將Spring的註解配置詳細的捋一遍,到時候會講到Bean的生命周期的。

繼承的BeanFactoryAware是在屬性賦值完成,執行構造方法後,postProcessBeforeInitialization才執行,而且,是在其他生命周期之前,而@Autowired註解就是依靠這個原理進行的自動註入。想要解決這個問題很簡單,就是把要賦值的成員變量放到其他生命周期中就可以。

下面介紹其中兩種辦法

第一種JSR250的@PostConstruct

@PostConstruct
public void init() {
	// 這裡放要執行的賦值
}

第二種是Spring的InitializingBean(定義初始化邏輯) 

繼承接口實現方法即可,這種直接放上完整用法

/**
 * @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()
        );
    }
}

設置完成後,問題解決!

推薦閱讀: