您好,登錄后才能下訂單哦!
這篇文章主要介紹了@Autowired注入空指針問題如何解決的相關(guān)知識(shí),內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價(jià)值,相信大家閱讀完這篇@Autowired注入空指針問題如何解決文章都會(huì)有所收獲,下面我們一起來看看吧。
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
本想應(yīng)該毫無問題,但是,報(bào)錯(cuò)了:
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
這就是答案。上面說所有的Spring的@Autowired注解都在構(gòu)造函數(shù)之后,而如果一個(gè)對(duì)象像下面代碼一樣聲明(private XXX = new XXX() 直接在類中聲明)的話,成員變量是在構(gòu)造函數(shù)之前進(jìn)行初始化的,甚至可以作為構(gòu)造函數(shù)的參數(shù)。
即 成員變量初始化 -> Constructor -> @Autowired
所以,在這個(gè)時(shí)候如果成員變量初始化時(shí)調(diào)用了利用@Autowired注解初始化的對(duì)象時(shí),必然會(huì)報(bào)空指針異常的啊。
真相大白了。如果解決呢?那就讓上面我寫的代碼的成員變量threadPool在@Autowired之后執(zhí)行就好了。
要想解決這個(gè)問題,首先要知道@Autowired的原理:
AutowiredAnnotationBeanPostProcessor 這個(gè)類
其實(shí)看到這個(gè)繼承結(jié)構(gòu),我心中已經(jīng)有解決辦法了。具體詳細(xì)為什么,等997的工作結(jié)束(無奈)我會(huì)在后續(xù)博客里將Spring的注解配置詳細(xì)的捋一遍,到時(shí)候會(huì)講到Bean的生命周期的。
繼承的BeanFactoryAware是在屬性賦值完成,執(zhí)行構(gòu)造方法后,postProcessBeforeInitialization才執(zhí)行,而且,是在其他生命周期之前,而@Autowired注解就是依靠這個(gè)原理進(jìn)行的自動(dòng)注入。想要解決這個(gè)問題很簡單,就是把要賦值的成員變量放到其他生命周期中就可以。
@PostConstruct public void init() { // 這里放要執(zhí)行的賦值 }
繼承接口實(shí)現(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() ); } }
關(guān)于“@Autowired注入空指針問題如何解決”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對(duì)“@Autowired注入空指針問題如何解決”知識(shí)都有一定的了解,大家如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。