最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談springboot自動(dòng)裝配原理

 更新時(shí)間:2021年05月14日 14:27:55   作者:向天再借500年  
作為Spring Boot的精髓,自動(dòng)配置原理首當(dāng)其沖.今天就帶大家了解一下springboot自動(dòng)裝配的原理,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們很有幫助,需要的朋友可以參考下

一、SpringBootApplication

@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 {

@Target(ElementType.TYPE)

設(shè)置當(dāng)前注解可以標(biāo)記在哪里,而SpringBootApplication只能用在類上面
還有一些其他的設(shè)置

public enum ElementType {
    /** Class, interface (including annotation type), or enum declaration */
    TYPE,

    /** Field declaration (includes enum constants) */
    FIELD,

    /** Method declaration */
    METHOD,

    /** Formal parameter declaration */
    PARAMETER,

    /** Constructor declaration */
    CONSTRUCTOR,

    /** Local variable declaration */
    LOCAL_VARIABLE,

    /** Annotation type declaration */
    ANNOTATION_TYPE,

    /** Package declaration */
    PACKAGE,

    /**
     * Type parameter declaration
     *
     * @since 1.8
     */
    TYPE_PARAMETER,

    /**
     * Use of a type
     *
     * @since 1.8
     */
    TYPE_USE,

    /**
     * Module declaration.
     *
     * @since 9
     */
    MODULE
}

@Retention(RetentionPolicy.RUNTIME)

public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     */
    SOURCE,

    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     */
    CLASS,

    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     *
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

SOURCE 當(dāng)編譯時(shí),注解將不會(huì)出現(xiàn)在class源文件中

CLASS 注解將會(huì)保留在class源文件中,但是不會(huì)被jvm加載,也就意味著不能通過(guò)反射去找到該注解,因?yàn)闆](méi)有加載到j(luò)ava虛擬機(jī)中

RUNTIME是既會(huì)保留在源文件中,也會(huì)被虛擬機(jī)加載

@Documented

java doc 會(huì)生成注解信息

@Inherited

是否會(huì)被繼承,就是如果一個(gè)子類繼承了使用了該注解的類,那么子類也能繼承該注解

@SpringBootConfiguration

標(biāo)注在某個(gè)類上,表示這是一個(gè)Spring Boot的配置類,本質(zhì)上也是使用了@Configuration注解

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {

@EnableAutoConfiguration

@EnableAutoConfiguration告訴SpringBoot開(kāi)啟自動(dòng)配置,會(huì)幫我們自動(dòng)去加載 自動(dòng)配置類

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {

@AutoConfigurationPackage

將當(dāng)前配置類所在包保存在BasePackages的Bean中。供Spring內(nèi)部使用

@Import({AutoConfigurationImportSelector.class})來(lái)加載配置類

配置文件的位置:META-INF/spring.factories,該配置文件中定義了大量的配置類,當(dāng)springboot啟動(dòng)時(shí),會(huì)自動(dòng)加載這些配置類,初始化Bean

并不是所有Bean都會(huì)被初始化,在配置類中使用Condition來(lái)加載滿足條件的Bean

二、案例

自定義redis-starter,要求當(dāng)導(dǎo)入redis坐標(biāo)時(shí),spirngboot自動(dòng)創(chuàng)建jedis的Bean

步驟

1.創(chuàng)建redis-spring-boot-autoconfigure模塊
2.創(chuàng)建redis-spring-boot-starter模塊,依賴redis-spring-boot-autoconfigure的模塊
3.在redis-spring-boot-autoconfigure模塊中初始化jedis的bean,并定義META-INF/spring.factories文件
4.在測(cè)試模塊中引入自定義的redis-starter依賴,測(cè)試獲取jedis的bean,操作redis

1.首先新建兩個(gè)模塊

在這里插入圖片描述
在這里插入圖片描述

刪除一些沒(méi)有用的東西,和啟動(dòng)類否則會(huì)報(bào)錯(cuò)

2.redis-spring-boot-starter模塊的pom.xml里面引入redis-spring-boot-autoconfigure的模塊的坐標(biāo)

3.RedisAutoConfiguration配置類

package com.blb;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class RedisAutoConfiguration {
//  提供Jedis的bean
    @Bean
    public Jedis jedis(RedisProperties redisProperties){
        return new Jedis(redisProperties.getHost(),redisProperties.getPort());
    }
}

RedisProperties

package com.blb;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "redis")
public class RedisProperties {
    private String host="localhost";
    private int port=6379;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}

@ComponentScan

掃描包 相當(dāng)于在spring.xml 配置中context:comonent-scan 但是并沒(méi)有指定basepackage,如果沒(méi)有指定spring底層會(huì)自動(dòng)掃描當(dāng)前配置類所有在的包

排除的類型

public enum FilterType {

	/**
	 * Filter candidates marked with a given annotation.
	 * @see org.springframework.core.type.filter.AnnotationTypeFilter
	 */
	ANNOTATION,

	/**
	 * Filter candidates assignable to a given type.
	 * @see org.springframework.core.type.filter.AssignableTypeFilter
	 */
	ASSIGNABLE_TYPE,

	/**
	 * Filter candidates matching a given AspectJ type pattern expression.
	 * @see org.springframework.core.type.filter.AspectJTypeFilter
	 */
	ASPECTJ,

	/**
	 * Filter candidates matching a given regex pattern.
	 * @see org.springframework.core.type.filter.RegexPatternTypeFilter
	 */
	REGEX,

	/** Filter candidates using a given custom
	 * {@link org.springframework.core.type.filter.TypeFilter} implementation.
	 */
	CUSTOM

}

ANNOTATION 默認(rèn)根據(jù)注解的完整限定名設(shè)置排除
ASSIGNABLE_TYPE 根據(jù)類的完整限定名排除
ASPECTJ 根據(jù)切面表達(dá)式設(shè)置排除
REGEX 根據(jù)正則表達(dá)式設(shè)置排除
CUSTOM 自定義設(shè)置排除

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })

按照自定義的方式來(lái)排除需要指定一個(gè)類,要實(shí)現(xiàn)TypeFilter接口,重寫match方法

public class TypeExcludeFilter implements TypeFilter, BeanFactoryAware {


public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        if (this.beanFactory instanceof ListableBeanFactory && this.getClass() == TypeExcludeFilter.class) {
            Iterator var3 = this.getDelegates().iterator();

            while(var3.hasNext()) {
                TypeExcludeFilter delegate = (TypeExcludeFilter)var3.next();
                if (delegate.match(metadataReader, metadataReaderFactory)) {
                    return true;
                }
            }
        }

        return false;
    }
}

TypeExcludeFilter :springboot對(duì)外提供的擴(kuò)展類, 可以供我們?nèi)グ凑瘴覀兊姆绞竭M(jìn)行排除

AutoConfigurationExcludeFilter :排除所有配置類并且是自動(dòng)配置類中里面的其中一個(gè)
示例

package com.blb.springbootyuanli.config;

import org.springframework.boot.context.TypeExcludeFilter;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;

import java.io.IOException;

public class MyTypeExcludeFilter extends TypeExcludeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        if(metadataReader.getClassMetadata().getClass()==UserConfig.class){
            return true;
        }
        return false;
    }
}

三、Condition

@Conditional是Spring4新提供的注解,它的作用是按照一定的條件進(jìn)行判斷,滿足條件給容器注冊(cè)bean,實(shí)現(xiàn)選擇性的創(chuàng)建bean的操作,該注解為條件裝配注解

源碼

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

	/**
	 * All {@link Condition} classes that must {@linkplain Condition#matches match}
	 * in order for the component to be registered.
	 */
	Class<? extends Condition>[] value();

}
@FunctionalInterface
public interface Condition {

	/**
	 * Determine if the condition matches.
	 * @param context the condition context
	 * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
	 * or {@link org.springframework.core.type.MethodMetadata method} being checked
	 * @return {@code true} if the condition matches and the component can be registered,
	 * or {@code false} to veto the annotated component's registration
	 */
	boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

重寫matches方法如果返回true spring則會(huì)幫你創(chuàng)建該對(duì)象,否則則不會(huì)

springboot提供的常用條件注解

@ConditionalOnProperty:判斷文件中是否有對(duì)應(yīng)屬性和值才實(shí)例化Bean
@ConditionalOnClass 檢查類在加載器中是否存在對(duì)應(yīng)的類,如果有則被注解修飾的類就有資格被 Spring 容器所注冊(cè),否則會(huì)被跳過(guò)。
@ConditionalOnBean 僅僅在當(dāng)前上下文中存在某個(gè)對(duì)象時(shí),才會(huì)實(shí)例化一個(gè) Bean
@ConditionalOnClass 某個(gè) CLASS 位于類路徑上,才會(huì)實(shí)例化一個(gè) Bean
@ConditionalOnExpression 當(dāng)表達(dá)式為 true 的時(shí)候,才會(huì)實(shí)例化一個(gè) Bean
@ConditionalOnMissingBean 僅僅在當(dāng)前上下文中不存在某個(gè)對(duì)象時(shí),才會(huì)實(shí)例化一個(gè) Bean
@ConditionalOnMissingClass 某個(gè) CLASS 類路徑上不存在的時(shí)候,才會(huì)實(shí)例化一個(gè) Bean

案例

在springIOC容器中有一個(gè)User的bean,現(xiàn)要求:
引入jedis坐標(biāo)后,加載該bean,沒(méi)導(dǎo)入則不加載

實(shí)體類

package com.blb.springbootyuanli.entity;

public class User {
    private String name;
    private int age;

	get/set

UserConfig

配置類

package com.blb.springbootyuanli.config;

import com.blb.springbootyuanli.condition.UserCondition;
import com.blb.springbootyuanli.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {
    @Bean
    @Conditional(UserCondition.class)
    public User user(){
        return new User();
    }
}

UserCondition

實(shí)現(xiàn)Condition接口,重寫matches方法

package com.blb.springbootyuanli.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

public class UserCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //思路判斷jedis的class文件是否存在
        boolean flag=true;
        try {

            Class<?> aClass = Class.forName("redis.clients.jedis.Jedis");

        } catch (ClassNotFoundException e) {
            flag=false;
        }
        return flag;
    }
}

啟動(dòng)類

package com.blb.springbootyuanli;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootYuanliApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext app = SpringApplication.run(SpringbootYuanliApplication.class, args);
        Object user = app.getBean("user");
        System.out.println(user);

    }

}

當(dāng)我們?cè)趐om.xml引入jedis的坐標(biāo)時(shí),就可以打印user對(duì)象,當(dāng)刪除jedis的坐標(biāo)時(shí),運(yùn)行就會(huì)報(bào)錯(cuò) No bean named ‘user' available

四、案例升級(jí)

將類的判斷定義為動(dòng)態(tài)的,判斷那個(gè)字節(jié)碼文件可以動(dòng)態(tài)指定

自定義一個(gè)注解

添加上元注解

package com.blb.springbootyuanli.condition;

import org.springframework.context.annotation.Conditional;

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD}) //該注解的添加范圍
@Retention(RetentionPolicy.RUNTIME) //該注解的生效時(shí)機(jī)
@Documented //生成javadoc的文檔

@Conditional(UserCondition.class)
public @interface UserClassCondition {
    String[] value();
}

UserConfig

package com.blb.springbootyuanli.config;

import com.blb.springbootyuanli.condition.UserClassCondition;
import com.blb.springbootyuanli.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {
    @Bean
    //@Conditional(UserCondition.class)
    @UserClassCondition("redis.clients.jedis.Jedis")
    public User user(){
        return new User();
    }
}
package com.blb.springbootyuanli.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

public class UserCondition implements Condition {
    /**
     *
     * @param context 上下文對(duì)象,用于獲取環(huán)境,ioc容器,classloader對(duì)象
     * @param metadata 注解元對(duì)象??梢垣@取注解定義的屬性值
     * @return
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //思路判斷指定屬性的class文件是否存在

        //獲取注解屬性值 value
        Map<String,Object> map=metadata.getAnnotationAttributes(UserClassCondition.class.getName());
        String[] values= (String[])map.get("value");

        boolean flag=true;
        try {
            for(String classname:values){
                Class<?> aClass = Class.forName(classname);
            }
            
        } catch (ClassNotFoundException e) {
            flag=false;
        }
        return flag;
    }
}

測(cè)試自帶的注解

package com.blb.springbootyuanli.config;

import com.blb.springbootyuanli.entity.User;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserConfig {
    @Bean
    //@Conditional(UserCondition.class)

    //@UserClassCondition("redis.clients.jedis.Jedis")
    @ConditionalOnProperty(name="age",havingValue = "18")
    //只有在配置文件中有age并且值為18spring在能注冊(cè)該bean
    public User user(){
        return new User();
    }
}

五、小結(jié)

自定義條件:

1.定義條件類:自定義類實(shí)現(xiàn)Condition接口,重寫重寫matches方法,在matches方法中進(jìn)行邏輯判斷,返回boolean值

2.matches方法的兩個(gè)參數(shù):
context:上下文對(duì)象,可以獲取屬性值,獲取類加載器,獲取BeanFactory
metadata:元數(shù)據(jù)對(duì)象,用于獲取注解屬性

3.判斷條件:在初始化Bean時(shí),使用@Conditional(條件類.class) 注解

到此這篇關(guān)于淺談springboot自動(dòng)裝配原理的文章就介紹到這了,更多相關(guān)springboot自動(dòng)裝配內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 一文看懂springboot實(shí)現(xiàn)短信服務(wù)功能

    一文看懂springboot實(shí)現(xiàn)短信服務(wù)功能

    項(xiàng)目中的短信服務(wù)基本上上都會(huì)用到,簡(jiǎn)單的注冊(cè)驗(yàn)證碼,消息通知等等都會(huì)用到。這篇文章主要介紹了springboot 實(shí)現(xiàn)短信服務(wù)功能,需要的朋友可以參考下
    2019-10-10
  • Maven 插件配置分層架構(gòu)深度解析

    Maven 插件配置分層架構(gòu)深度解析

    這篇文章主要介紹了Maven 插件配置分層架構(gòu)深度解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2025-05-05
  • Mybatis generator如何自動(dòng)生成代碼

    Mybatis generator如何自動(dòng)生成代碼

    這篇文章主要介紹了Mybatis generator如何自動(dòng)生成代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • Java并發(fā)編程之ThreadLocal詳解

    Java并發(fā)編程之ThreadLocal詳解

    今天給大家?guī)?lái)的是Java并發(fā)編程的相關(guān)知識(shí),文中對(duì)ThreadLocal做了非常詳細(xì)的分析及介紹,對(duì)小伙伴們很有幫助,需要的朋友可以參考下
    2021-06-06
  • Java基礎(chǔ)之?dāng)?shù)組詳解

    Java基礎(chǔ)之?dāng)?shù)組詳解

    這篇文章主要介紹了Java基礎(chǔ)之?dāng)?shù)組詳解,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)java的小伙伴們有很好的幫助,需要的朋友可以參考下
    2021-04-04
  • 如何擴(kuò)展Spring Cache實(shí)現(xiàn)支持多級(jí)緩存

    如何擴(kuò)展Spring Cache實(shí)現(xiàn)支持多級(jí)緩存

    這篇文章主要介紹了如何擴(kuò)展Spring Cache實(shí)現(xiàn)支持多級(jí)緩存,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11
  • Java?Post請(qǐng)求發(fā)送form-data表單參數(shù)詳細(xì)示例代碼

    Java?Post請(qǐng)求發(fā)送form-data表單參數(shù)詳細(xì)示例代碼

    POST請(qǐng)求是一種常見(jiàn)的網(wǎng)絡(luò)通信操作,用于向服務(wù)器發(fā)送數(shù)據(jù),這種請(qǐng)求通常用于上傳文件或者提交包含大量數(shù)據(jù)的表單,這篇文章主要介紹了Java?Post請(qǐng)求發(fā)送form-data表單參數(shù)的相關(guān)資料,需要的朋友可以參考下
    2025-07-07
  • Java Spring三級(jí)緩存

    Java Spring三級(jí)緩存

    三級(jí)緩存就是在Bean生成流程中保存Bean對(duì)象三種形態(tài)的三個(gè)Map集合,這個(gè)三級(jí)緩存就是為了解決循環(huán)依賴,本文給大家介紹Java Spring三級(jí)緩存,感興趣的朋友一起看看吧
    2025-06-06
  • 詳解SpringBoot中如何使用Reactor模型

    詳解SpringBoot中如何使用Reactor模型

    Reactor模型主要提供了一種在Java虛擬機(jī)上構(gòu)建非阻塞應(yīng)用的方式,這種方式使用了響應(yīng)式編程原理,通過(guò)響應(yīng)式流標(biāo)準(zhǔn)來(lái)實(shí)現(xiàn),下面我們就來(lái)看看它在SpringBoot中是如何使用的吧
    2024-04-04
  • springboot啟動(dòng)報(bào)錯(cuò):application?startup?failed問(wèn)題

    springboot啟動(dòng)報(bào)錯(cuò):application?startup?failed問(wèn)題

    這篇文章主要介紹了springboot啟動(dòng)報(bào)錯(cuò):application?startup?failed問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-07-07

最新評(píng)論

宜章县| 大理市| 芜湖市| 斗六市| 南漳县| 台湾省| 朝阳县| 华容县| 南阳市| 始兴县| 安仁县| 恩平市| 弥渡县| 望城县| 白城市| 黄骅市| 宜州市| 沧州市| 双鸭山市| 梅河口市| 陆川县| 大渡口区| 彭水| 白水县| 连州市| 兴和县| 孝感市| 萨迦县| 抚顺县| 藁城市| 崇左市| 德钦县| 德兴市| 博客| 微博| 定陶县| 壤塘县| 石楼县| 嘉兴市| 大连市| 凤凰县|