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

Java中Spring擴(kuò)展點(diǎn)詳解

 更新時(shí)間:2022年06月16日 09:15:00   作者:hi wei  
這篇文章主要介紹了Java中Spring技巧之?dāng)U展點(diǎn)的應(yīng)用,下文Spring容器的啟動(dòng)流程圖展開其內(nèi)容的相關(guān)資料,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

如何在所有Bean創(chuàng)建完后做擴(kuò)展

方式一

Spring在容器刷新完成后會(huì)注冊(cè)ContextRefreshedEvent。

所以可以自定義事件監(jiān)聽器監(jiān)聽該事件進(jìn)行擴(kuò)展。

監(jiān)聽器實(shí)現(xiàn):

@Component
public class ContextRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        System.out.println("容器初始化完成,開始進(jìn)行擴(kuò)展!");
    }
}

方式二

Spring在所有bean注冊(cè)完成后,會(huì)檢查bean是否實(shí)現(xiàn)了SmartInitializingSingleton接口,如果實(shí)現(xiàn)了,會(huì)回調(diào)改類的afterSingletonsInstantiated()方法,我們可以在方法里實(shí)現(xiàn)擴(kuò)展。

實(shí)現(xiàn)SmartInitializingSingleton接口:

/**
 * @author zhw
 * @description
 * @date 2021-09-29 15:28
 */
@Component
public class SmartInitializingSingletonTest implements SmartInitializingSingleton {
    @Override
    public void afterSingletonsInstantiated() {
        System.out.println("所有單例bean注冊(cè)完成,開始擴(kuò)展!");
    }
}

Spring通過(guò)initPropertySources擴(kuò)展方法設(shè)置環(huán)境配置

Spring的prepareRefresh()方法中有initPropertySources()方法,但是默認(rèn)容器是未實(shí)現(xiàn)這個(gè)方法的。我們可以實(shí)現(xiàn)該方法進(jìn)行擴(kuò)展。

實(shí)現(xiàn)自定義擴(kuò)展容器:

/**
 * @author zhw
 * @description
 * @date 2021-09-29 16:05
 */
public class ExtensionContext extends AnnotationConfigApplicationContext {
    public ExtensionContext(Class<MainConfig> mainConfigClass) {
        super(mainConfigClass);
    }
    @Override
    protected void initPropertySources() {
        //設(shè)置一些必須的環(huán)境變量
        getEnvironment().setRequiredProperties("appName");
    }
}

設(shè)置環(huán)境變量:

測(cè)試類:

public class MyContextTest {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext annotationConfigApplicationContext = new ExtensionContext(MainConfig.class);
    }
}

結(jié)果:

@Import進(jìn)行擴(kuò)展

方式一:實(shí)現(xiàn)ImportBeanDefinitionRegistrar接口

例如開啟AOP注解,使用AspectJAutoProxyRegistrar.class

AspectJAutoProxyRegistrar實(shí)現(xiàn)了ImportBeanDefinitionRegistrar接口,進(jìn)行BeadDefinition的注冊(cè):

方式二:實(shí)現(xiàn)ImportSelector接口

ImportSelector接口的selectImports方法返回的是要注入類的全類名數(shù)組。spring會(huì)根據(jù)全類名注冊(cè)bean。

例如:開啟事務(wù)管理功能就是使用實(shí)現(xiàn)ImportSelector接口進(jìn)行擴(kuò)展。

看下TransactionManagementConfigurationSelector.class:

到此這篇關(guān)于Java中Spring擴(kuò)展點(diǎn)詳解的文章就介紹到這了,更多相關(guān)Java Spring擴(kuò)展點(diǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論