热门标签 | HotTags
当前位置:  开发笔记 > 后端 > 正文

浅谈springboot自动装配原理

作为SpringBoot的精髓,自动配置原理首当其冲.今天就带大家了解一下springboot自动装配的原理,文中有非常详细的代码示例,对正在学习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)

设置当前注解可以标记在哪里,而SpringBootApplication只能用在类上面
还有一些其他的设置

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 当编译时,注解将不会出现在class源文件中

CLASS 注解将会保留在class源文件中,但是不会被jvm加载,也就意味着不能通过反射去找到该注解,因为没有加载到java虚拟机中

RUNTIME是既会保留在源文件中,也会被虚拟机加载

@Documented

java doc 会生成注解信息

@Inherited

是否会被继承,就是如果一个子类继承了使用了该注解的类,那么子类也能继承该注解

@SpringBootConfiguration

标注在某个类上,表示这是一个Spring Boot的配置类,本质上也是使用了@Configuration注解

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

@EnableAutoConfiguration

@EnableAutoConfiguration告诉SpringBoot开启自动配置,会帮我们自动去加载 自动配置类

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

@AutoConfigurationPackage

将当前配置类所在包保存在BasePackages的Bean中。供Spring内部使用

@Import({AutoConfigurationImportSelector.class})来加载配置类

配置文件的位置:META-INF/spring.factories,该配置文件中定义了大量的配置类,当springboot启动时,会自动加载这些配置类,初始化Bean

并不是所有Bean都会被初始化,在配置类中使用Condition来加载满足条件的Bean

二、案例

自定义redis-starter,要求当导入redis坐标时,spirngboot自动创建jedis的Bean

步骤

1.创建redis-spring-boot-autoconfigure模块
2.创建redis-spring-boot-starter模块,依赖redis-spring-boot-autoconfigure的模块
3.在redis-spring-boot-autoconfigure模块中初始化jedis的bean,并定义META-INF/spring.factories文件
4.在测试模块中引入自定义的redis-starter依赖,测试获取jedis的bean,操作redis

1.首先新建两个模块

在这里插入图片描述
在这里插入图片描述

删除一些没有用的东西,和启动类否则会报错

2.redis-spring-boot-starter模块的pom.xml里面引入redis-spring-boot-autoconfigure的模块的坐标

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

扫描包 相当于在spring.xml 配置中context:comonent-scan 但是并没有指定basepackage,如果没有指定spring底层会自动扫描当前配置类所有在的包

排除的类型

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 默认根据注解的完整限定名设置排除
ASSIGNABLE_TYPE 根据类的完整限定名排除
ASPECTJ 根据切面表达式设置排除
REGEX 根据正则表达式设置排除
CUSTOM 自定义设置排除

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

按照自定义的方式来排除需要指定一个类,要实现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对外提供的扩展类, 可以供我们去按照我们的方式进行排除

AutoConfigurationExcludeFilter :排除所有配置类并且是自动配置类中里面的其中一个
示例

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新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册bean,实现选择性的创建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<&#63; 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则会帮你创建该对象,否则则不会

springboot提供的常用条件注解

@ConditionalOnProperty:判断文件中是否有对应属性和值才实例化Bean
@ConditionalOnClass 检查类在加载器中是否存在对应的类,如果有则被注解修饰的类就有资格被 Spring 容器所注册,否则会被跳过。
@ConditionalOnBean 仅仅在当前上下文中存在某个对象时,才会实例化一个 Bean
@ConditionalOnClass 某个 CLASS 位于类路径上,才会实例化一个 Bean
@ConditionalOnExpression 当表达式为 true 的时候,才会实例化一个 Bean
@ConditionalOnMissingBean 仅仅在当前上下文中不存在某个对象时,才会实例化一个 Bean
@ConditionalOnMissingClass 某个 CLASS 类路径上不存在的时候,才会实例化一个 Bean

案例

在springIOC容器中有一个User的bean,现要求:
引入jedis坐标后,加载该bean,没导入则不加载

实体类

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

实现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<&#63;> aClass = Class.forName("redis.clients.jedis.Jedis");

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

启动类

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);

    }

}

当我们在pom.xml引入jedis的坐标时,就可以打印user对象,当删除jedis的坐标时,运行就会报错 No bean named ‘user' available

四、案例升级

将类的判断定义为动态的,判断那个字节码文件可以动态指定

自定义一个注解

添加上元注解

package com.blb.springbootyuanli.condition;

import org.springframework.context.annotation.Conditional;

import java.lang.annotation.*;

@Target({ElementType.TYPE, ElementType.METHOD}) //该注解的添加范围
@Retention(RetentionPolicy.RUNTIME) //该注解的生效时机
@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 上下文对象,用于获取环境,ioc容器,classloader对象
     * @param metadata 注解元对象。可以获取注解定义的属性值
     * @return
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //思路判断指定属性的class文件是否存在

        //获取注解属性值 value
        Map map=metadata.getAnnotationAttributes(UserClassCondition.class.getName());
        String[] values= (String[])map.get("value");

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

测试自带的注解

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在能注册该bean
    public User user(){
        return new User();
    }
}

五、小结

自定义条件:

1.定义条件类:自定义类实现Condition接口,重写重写matches方法,在matches方法中进行逻辑判断,返回boolean值

2.matches方法的两个参数:
context:上下文对象,可以获取属性值,获取类加载器,获取BeanFactory
metadata:元数据对象,用于获取注解属性

3.判断条件:在初始化Bean时,使用@Conditional(条件类.class) 注解

到此这篇关于浅谈springboot自动装配原理的文章就介绍到这了,更多相关springboot自动装配内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 本文介绍了Java工具类库Hutool,该工具包封装了对文件、流、加密解密、转码、正则、线程、XML等JDK方法的封装,并提供了各种Util工具类。同时,还介绍了Hutool的组件,包括动态代理、布隆过滤、缓存、定时任务等功能。该工具包可以简化Java代码,提高开发效率。 ... [详细]
  • 单点登录原理及实现方案详解
    本文详细介绍了单点登录的原理及实现方案,其中包括共享Session的方式,以及基于Redis的Session共享方案。同时,还分享了作者在应用环境中所遇到的问题和经验,希望对读者有所帮助。 ... [详细]
  • Spring常用注解(绝对经典),全靠这份Java知识点PDF大全
    本文介绍了Spring常用注解和注入bean的注解,包括@Bean、@Autowired、@Inject等,同时提供了一个Java知识点PDF大全的资源链接。其中详细介绍了ColorFactoryBean的使用,以及@Autowired和@Inject的区别和用法。此外,还提到了@Required属性的配置和使用。 ... [详细]
  • 本文介绍了Linux Shell中括号和整数扩展的使用方法,包括命令组、命令替换、初始化数组以及算术表达式和逻辑判断的相关内容。括号中的命令将会在新开的子shell中顺序执行,括号中的变量不能被脚本余下的部分使用。命令替换可以用于将命令的标准输出作为另一个命令的输入。括号中的运算符和表达式符合C语言运算规则,可以用在整数扩展中进行算术计算和逻辑判断。 ... [详细]
  • 使用正则表达式爬取36Kr网站首页新闻的操作步骤和代码示例
    本文介绍了使用正则表达式来爬取36Kr网站首页所有新闻的操作步骤和代码示例。通过访问网站、查找关键词、编写代码等步骤,可以获取到网站首页的新闻数据。代码示例使用Python编写,并使用正则表达式来提取所需的数据。详细的操作步骤和代码示例可以参考本文内容。 ... [详细]
  • 深度学习中的Vision Transformer (ViT)详解
    本文详细介绍了深度学习中的Vision Transformer (ViT)方法。首先介绍了相关工作和ViT的基本原理,包括图像块嵌入、可学习的嵌入、位置嵌入和Transformer编码器等。接着讨论了ViT的张量维度变化、归纳偏置与混合架构、微调及更高分辨率等方面。最后给出了实验结果和相关代码的链接。本文的研究表明,对于CV任务,直接应用纯Transformer架构于图像块序列是可行的,无需依赖于卷积网络。 ... [详细]
  • OO第一单元自白:简单多项式导函数的设计与bug分析
    本文介绍了作者在学习OO的第一次作业中所遇到的问题及其解决方案。作者通过建立Multinomial和Monomial两个类来实现多项式和单项式,并通过append方法将单项式组合为多项式,并在此过程中合并同类项。作者还介绍了单项式和多项式的求导方法,并解释了如何利用正则表达式提取各个单项式并进行求导。同时,作者还对自己在输入合法性判断上的不足进行了bug分析,指出了自己在处理指数情况时出现的问题,并总结了被hack的原因。 ... [详细]
  • 本文介绍了在处理不规则数据时如何使用Python自动提取文本中的时间日期,包括使用dateutil.parser模块统一日期字符串格式和使用datefinder模块提取日期。同时,还介绍了一段使用正则表达式的代码,可以支持中文日期和一些特殊的时间识别,例如'2012年12月12日'、'3小时前'、'在2012/12/13哈哈'等。 ... [详细]
  • Python爬虫中使用正则表达式的方法和注意事项
    本文介绍了在Python爬虫中使用正则表达式的方法和注意事项。首先解释了爬虫的四个主要步骤,并强调了正则表达式在数据处理中的重要性。然后详细介绍了正则表达式的概念和用法,包括检索、替换和过滤文本的功能。同时提到了re模块是Python内置的用于处理正则表达式的模块,并给出了使用正则表达式时需要注意的特殊字符转义和原始字符串的用法。通过本文的学习,读者可以掌握在Python爬虫中使用正则表达式的技巧和方法。 ... [详细]
  • 本文介绍了绕过WAF的XSS检测机制的方法,包括确定payload结构、测试和混淆。同时提出了一种构建XSS payload的方法,该payload与安全机制使用的正则表达式不匹配。通过清理用户输入、转义输出、使用文档对象模型(DOM)接收器和源、实施适当的跨域资源共享(CORS)策略和其他安全策略,可以有效阻止XSS漏洞。但是,WAF或自定义过滤器仍然被广泛使用来增加安全性。本文的方法可以绕过这种安全机制,构建与正则表达式不匹配的XSS payload。 ... [详细]
  • 小程序wxs中的时间格式化以及格式化时间和date时间互转
    本文介绍了在小程序wxs中进行时间格式化操作的问题,并提供了解决方法。同时还介绍了格式化时间和date时间的互相转换的方法。 ... [详细]
  • HTML5网页模板怎么加百度统计?
    本文介绍了如何在HTML5网页模板中加入百度统计,并对模板文件、css样式表、js插件库等内容进行了说明。同时还解答了关于HTML5网页模板的使用方法、表单提交、域名和空间的问题,并介绍了如何使用Visual Studio 2010创建HTML5模板。此外,还提到了使用Jquery编写美好的HTML5前端框架模板的方法,以及制作企业HTML5网站模板和支持HTML5的CMS。 ... [详细]
  • 统一知识图谱学习和建议:更好地理解用户偏好
    本文介绍了一种将知识图谱纳入推荐系统的方法,以提高推荐的准确性和可解释性。与现有方法不同的是,本方法考虑了知识图谱的不完整性,并在知识图谱中传输关系信息,以更好地理解用户的偏好。通过大量实验,验证了本方法在推荐任务和知识图谱完成任务上的优势。 ... [详细]
  • 背景应用安全领域,各类攻击长久以来都危害着互联网上的应用,在web应用安全风险中,各类注入、跨站等攻击仍然占据着较前的位置。WAF(Web应用防火墙)正是为防御和阻断这类攻击而存在 ... [详细]
  • 本文详细介绍了Python中正则表达式和re模块的使用方法。首先解释了转义符的作用,以及如何在字符串中包含特殊字符。然后介绍了re模块的功能和常用方法。通过学习本文,读者可以掌握正则表达式的基本概念和使用技巧,进一步提高Python编程能力。 ... [详细]
author-avatar
寺儿沟小晨晨
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有