欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年02月24日 11:52:19   作者:Hermione?Granger  
這篇文章主要介紹了解決@Autowired注入空指針問題(利用Bean的生命周期),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

今天做項(xiàng)目的時(shí)候遇到一個(gè)問題,需要將線程池的參數(shù)抽取到y(tǒng)ml文件里進(jìn)行設(shè)置。這不是so easy嗎?

我就寫出了下面這樣的代碼進(jìn)行抽取

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

空指針異常?檢查好幾遍配置沒錯(cuò)。因?yàn)楣鹃_發(fā)環(huán)境沒法上網(wǎng),只好拖到下班google了一下,結(jié)合我比較深厚的基礎(chǔ)(自戀一下),

問題輕松解決

這就是答案。上面說所有的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è)問題很簡(jiǎn)單,就是把要賦值的成員變量放到其他生命周期中就可以。

下面介紹其中兩種辦法

第一種JSR250的@PostConstruct

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

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

繼承接口實(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()
        );
    }
}

設(shè)置完成后,問題解決!

相關(guān)文章

  • SpringBoot中的自定義Starter解讀

    SpringBoot中的自定義Starter解讀

    這篇文章主要介紹了SpringBoot中的自定義Starter解讀,啟動(dòng)器模塊其實(shí)是一個(gè)空的jar文件,里面沒有什么類、接口,僅僅是提供輔助性依賴管理,這些依賴可能用于自動(dòng)裝配或者其他類庫(kù),需要的朋友可以參考下
    2023-12-12
  • 解決Java & Idea啟動(dòng)tomcat的中文亂碼問題

    解決Java & Idea啟動(dòng)tomcat的中文亂碼問題

    這篇文章主要介紹了Java & Idea啟動(dòng)tomcat的中文亂碼問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-07-07
  • SpringBoot中配置Web靜態(tài)資源路徑的方法

    SpringBoot中配置Web靜態(tài)資源路徑的方法

    這篇文章主要介紹了SpringBoot中配置Web靜態(tài)資源路徑的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 詳解MyBatis逆向工程

    詳解MyBatis逆向工程

    本篇文章主要介紹了詳解MyBatis逆向工程,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-01-01
  • 兩個(gè)jar包下相同包名類名引入沖突的解決方法

    兩個(gè)jar包下相同包名類名引入沖突的解決方法

    本文主要介紹了兩個(gè)jar包下相同包名類名引入沖突的解決方法,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • RocketMQ中的消費(fèi)模式和消費(fèi)策略詳解

    RocketMQ中的消費(fèi)模式和消費(fèi)策略詳解

    這篇文章主要介紹了RocketMQ中的消費(fèi)模式和消費(fèi)策略詳解,RocketMQ 是基于發(fā)布訂閱模型的消息中間件,所謂的發(fā)布訂閱就是說,consumer 訂閱了 broker 上的某個(gè) topic,當(dāng) producer 發(fā)布消息到 broker 上的該 topic 時(shí),consumer 就能收到該條消息,需要的朋友可以參考下
    2023-10-10
  • Java學(xué)習(xí)筆記之Maven篇

    Java學(xué)習(xí)筆記之Maven篇

    今天來回顧下Java學(xué)習(xí)筆記,文中對(duì)maven的核心,maven的結(jié)構(gòu)以及maven能做什么都作出了詳細(xì)的解釋,,需要的朋友可以參考下
    2021-05-05
  • JAVA對(duì)象JSON數(shù)據(jù)互相轉(zhuǎn)換的四種常見情況

    JAVA對(duì)象JSON數(shù)據(jù)互相轉(zhuǎn)換的四種常見情況

    這篇文章主要介紹了JAVA對(duì)象JSON數(shù)據(jù)互相轉(zhuǎn)換的四種常見情況,需要的朋友可以參考下
    2014-04-04
  • 詳解Java Ajax jsonp 跨域請(qǐng)求

    詳解Java Ajax jsonp 跨域請(qǐng)求

    本篇文章主要介紹了詳解Java Ajax jsonp 跨域請(qǐng)求,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Java實(shí)現(xiàn)阿里云短信接口的示例

    Java實(shí)現(xiàn)阿里云短信接口的示例

    這篇文章主要介紹了Java實(shí)現(xiàn)阿里云短信接口的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09

最新評(píng)論