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