亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

SpringBoot開發(fā)實(shí)戰(zhàn)之自動(dòng)配置

 更新時(shí)間:2021年08月12日 11:21:19   作者:懵懂小虎  
SpringBoot的核心就是自動(dòng)配置,自動(dòng)配置又是基于條件判斷來(lái)配置Bean,下面這篇文章主要給大家介紹了關(guān)于SpringBoot開發(fā)實(shí)戰(zhàn)之自動(dòng)配置的相關(guān)資料,需要的朋友可以參考下

在介紹SpringBoot的自動(dòng)配置之前,先了解下注解@Import的使用,SpringBoot的@Enable*開頭的注解底層依賴于@Import注解導(dǎo)入一些類,使用@Import導(dǎo)入的類會(huì)被Spring加載到IOC容器中,而@Import提供了以下4中用法:

  • 直接導(dǎo)入Bean
  • 通過配置類導(dǎo)入Bean
  • 導(dǎo)入ImportSelector實(shí)現(xiàn)類,一般用于加載配置文件的類
  • 導(dǎo)入ImportBeanDefinitionRegistrar實(shí)現(xiàn)類

下面來(lái)分別介紹這幾種用法。

直接導(dǎo)入Bean就比較簡(jiǎn)單了,新建一個(gè)User類

public class User{
    private String name;
    private String address;
}

然后在啟動(dòng)類上使用@Import注解導(dǎo)入即可

@SpringBootApplication
@Import(User.class)
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        System.out.println(context.getBean(User.class));
    }
}

這里需要注意的是,通過上下文獲取Bean時(shí),需要使用Bean的class,因?yàn)橥ㄟ^Bean的方式導(dǎo)入,Spring存入IOC容器,是用類的全類名存儲(chǔ)的??梢允褂蒙舷挛牡膅etBeansOfType方法查看,返回的是Map對(duì)象。

{com.tenghu.sbc.entity.User=User(name=null, age=0)}

從返回的結(jié)果可以看出,key就是存的User的全類名。

通過配置類導(dǎo)入Bean,創(chuàng)建一個(gè)配置類;

public class UserConfig {
    @Bean(name = "user")
    public User user(){
        return new User();
    }
}

然后通過@Import導(dǎo)入這個(gè)配置類

@SpringBootApplication
@Import(UserConfig.class)
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class,args);
        System.out.println(context.getBean(User.class));
    }
}

通過配置類的方式可以在配置類里面定義多個(gè)Bean,當(dāng)導(dǎo)入配置類時(shí),配置類下定義的Bean都會(huì)被導(dǎo)入。

導(dǎo)入ImportSelector實(shí)現(xiàn)類

public class MyImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{User.class.getName()};
    }
}

實(shí)現(xiàn)ImportSelector類,必須實(shí)現(xiàn)selectImports,然后返回需要導(dǎo)入的Bean。與上面一樣使用@Import導(dǎo)入這個(gè)實(shí)現(xiàn)類。

@Import(MyImportSelector.class)

導(dǎo)入ImportBeanDefinitionRegistrar實(shí)現(xiàn)類

public class MyImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(User.class).getBeanDefinition();
        registry.registerBeanDefinition("user",beanDefinition);
    }
}

使用方式一樣,通過@Import導(dǎo)入

@Import(MyImportBeanDefinitionRegistrar.class)

了解完@Import的使用,接下來(lái)可以來(lái)看下SpringBoot的自動(dòng)配置是怎么處理的。從上面的啟動(dòng)類,使用SpringBoot就用了一個(gè)注解@SpringBootApplication,可以打開這個(gè)注解的源碼看下:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication

用到這樣一個(gè)注解@EnableAutoConfiguration注解。底層使用@Import導(dǎo)入上面第三種方式AutoConfigurationImportSelector。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {};

    String[] excludeName() default {};
}

進(jìn)入源碼找到實(shí)現(xiàn)了selectImports方法

public String[] selectImports(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return NO_IMPORTS;
    } else {
        AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(annotationMetadata);
        return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
    }
}

通過調(diào)用方法getAutoConfigurationEntry

protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
    if (!this.isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    } else {
        AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
        List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
        configurations = this.removeDuplicates(configurations);
        Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
        this.checkExcludedClasses(configurations, exclusions);
        configurations.removeAll(exclusions);
        configurations = this.getConfigurationClassFilter().filter(configurations);
        this.fireAutoConfigurationImportEvents(configurations, exclusions);
        return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
    }
}

這里主要的看調(diào)用這個(gè)方法getCandidateConfigurations,返回的就是要自動(dòng)加載的Bean

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
}

通過META-INF/spring.factories配置文件里的EnableAutoConfiguration獲取配置的Bean

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
.....

太多了,有興趣的可以查看Spring的xxx-autoconfigure包。將讀取到的配置最終返回給selectImports,然后通過工具類StringUtils.toStringArray轉(zhuǎn)換為字符串?dāng)?shù)組返回給@Import,從而實(shí)現(xiàn)自動(dòng)配置。第三方包只要是xxx-autoconfigure結(jié)尾的包,META-INF都有spring.factories,這個(gè)名字是固定寫法。都可以被SpringBoot識(shí)別并且進(jìn)行自動(dòng)配置,前提是需要配置到org.springframework.boot.autoconfigure.EnableAutoConfiguration下。

從以上總結(jié)來(lái)看,SpringBoot的自動(dòng)配置原理如下:

  • @EnableAutoConfiguration注解內(nèi)部使用Import(AutoConfigurationImportSelector.class)來(lái)加載配置類
  • 通過配置文件:META-INF/spring.factories,配置大量的配置類,SpringBoot啟動(dòng)時(shí)就會(huì)自動(dòng)加載這些類并初始化的Bean。

這里需要說(shuō)明一點(diǎn),并不是所有配置到配置文件的Bean都會(huì)被初始化,需要符合配置類中使用Condition來(lái)加載滿足條件的Bean。比如我們打開RedisAutoConfiguration的源碼查看:

@Configuration(
    proxyBeanMethods = false
)
@ConditionalOnClass({RedisOperations.class})
@EnableConfigurationProperties({RedisProperties.class})
@Import({LettuceConnectionConfiguration.class, JedisConnectionConfiguration.class})
public class RedisAutoConfiguration {
    public RedisAutoConfiguration() {
    }

    @Bean
    @ConditionalOnMissingBean(
        name = {"redisTemplate"}
    )
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnSingleCandidate(RedisConnectionFactory.class)
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

類上面有這么個(gè)注解@ConditionalOnClass({RedisOperations.class}),意思就是需要RedisOperations類存在的情況下,才自動(dòng)加載;這還不算完,繼續(xù)查看下面的方法上有個(gè)@ConditionalOnMissingBean(name = {"redisTemplate"}),這里的意思是,當(dāng)其他地方?jīng)]有redisTemplate實(shí)例化這個(gè)Bean時(shí),才自動(dòng)加載。符合這兩個(gè)條件,SpringBoot才會(huì)進(jìn)行自動(dòng)加載并初始化。

總結(jié)

到此這篇關(guān)于SpringBoot開發(fā)實(shí)戰(zhàn)之自動(dòng)配置的文章就介紹到這了,更多相關(guān)SpringBoot自動(dòng)配置內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • springboot-dubbo cannot be cast to問題及解決

    springboot-dubbo cannot be cast to問題及解決

    這篇文章主要介紹了springboot-dubbo cannot be cast to問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • 淺談Java中的Filter過濾器

    淺談Java中的Filter過濾器

    本篇文章主要介紹了淺談Java中的Filter過濾器,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧
    2017-02-02
  • Java實(shí)現(xiàn)俄羅斯方塊游戲的示例代碼

    Java實(shí)現(xiàn)俄羅斯方塊游戲的示例代碼

    俄羅斯方塊是一個(gè)最初由阿列克謝帕吉特諾夫在蘇聯(lián)設(shè)計(jì)和編程的益智類視頻游戲。本文將利用Java實(shí)現(xiàn)這一經(jīng)典的小游戲,感興趣的可以動(dòng)手試一試
    2022-03-03
  • java?工作流引擎設(shè)計(jì)實(shí)現(xiàn)解析流程定義文件

    java?工作流引擎設(shè)計(jì)實(shí)現(xiàn)解析流程定義文件

    這篇文章主要為大家介紹了java?工作流引擎設(shè)計(jì)與實(shí)現(xiàn)及流程定義文件解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • SpringBoot整合定時(shí)任務(wù)之實(shí)現(xiàn)Scheduled注解的過程(一個(gè)注解全解決)

    SpringBoot整合定時(shí)任務(wù)之實(shí)現(xiàn)Scheduled注解的過程(一個(gè)注解全解決)

    這篇文章主要介紹了SpringBoot整合定時(shí)任務(wù)之實(shí)現(xiàn)Scheduled注解的過程(一個(gè)注解全解決),本文通過使用場(chǎng)景分析給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-09-09
  • spring event 事件異步處理方式(發(fā)布,監(jiān)聽,異步處理)

    spring event 事件異步處理方式(發(fā)布,監(jiān)聽,異步處理)

    這篇文章主要介紹了spring event 事件異步處理方式(發(fā)布,監(jiān)聽,異步處理),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-02-02
  • Servlet實(shí)現(xiàn)簡(jiǎn)單的用戶登錄功能實(shí)例代碼

    Servlet實(shí)現(xiàn)簡(jiǎn)單的用戶登錄功能實(shí)例代碼

    這篇文章主要給大家介紹了關(guān)于利用Servlet實(shí)現(xiàn)簡(jiǎn)單的用戶登錄功能的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • Transactional注解導(dǎo)致Spring Bean定時(shí)任務(wù)失效的解決方法

    Transactional注解導(dǎo)致Spring Bean定時(shí)任務(wù)失效的解決方法

    這篇文章主要介紹了Transactional注解導(dǎo)致Spring Bean定時(shí)任務(wù)失效的解決方法,文中通過代碼示例介紹的非常詳細(xì),對(duì)大家解決問題有一定的幫助,需要的朋友可以參考下
    2024-10-10
  • Eclipse配置maven環(huán)境的圖文教程

    Eclipse配置maven環(huán)境的圖文教程

    下面小編就為大家?guī)?lái)一篇Eclipse配置maven環(huán)境的圖文教程。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來(lái)看看吧
    2017-11-11
  • Redis之GEO存儲(chǔ)地理位置信息的使用

    Redis之GEO存儲(chǔ)地理位置信息的使用

    在外賣軟件中的附近的美食店鋪、外賣小哥的距離,打車軟件附近的車輛,交友軟件中附近的小姐姐。我們都可以利用redis的GEO地理位置計(jì)算得出。本文就來(lái)詳細(xì)的介紹一下
    2021-10-10

最新評(píng)論