前言

        最近在学习Spring Boot相关的课程,过程中以笔记的形式记录下来,方便以后回忆,同时也在这里和大家探讨探讨,文章中有漏的或者有补充的、错误的都希望大家能够及时提出来,本人在此先谢谢了!

开始之前呢,希望大家带着几个问题去学习:

1、Spring注解驱动是什么?

2、这个功能在什么时代背景下发明产生的?

3、这个功能有什么用?

4、怎么实现的?

5、优点和缺点是什么?

6、这个功能能应用在工作中?

这是对自我的提问,我认为带着问题去学习,是一种更好的学习方式,有利于加深理解。好了,接下来进入主题。

1、起源

        我们先来简单的聊聊Spring注解的发展史。Spring1.x时代,那时候注解的概念刚刚兴起,仅支持如 @Transactional 等注解。到了2.x时代Spring的注解体系有了雏形,引入了 @Autowired 、 @Controller 这一系列骨架式的注解。3.x是黄金时代,它除了引入 @Enable 模块驱动概念,加快了Spring注解体系的成型,还引入了配置类 @Configuration 及 @ComponentScan ,使我们可以抛弃XML配置文件的形式,全面拥抱Spring注解,但Spring并未完全放弃XML配置文件,它提供了 @ImportResource 允许导入遗留的XML配置文件。此外还提供了 @Import 允许导入一个或多个Java类成为Spring Bean。4.X则趋于完善,引入了条件化注解 @Conditional ,使装配更加的灵活。当下是5.X时代,是SpringBoot2.0的底层核心框架,目前来看,变化不是很大,但也引入了一个 @Indexed 注解,主要是用来提升启动性能的。好了,以上是Spring注解的发展史,接下来我们对Spring注解体系的几个议题进行讲解。

2、Spring 模式注解

        模式注解是一种用于声明在应用中扮演“组件”角色的注解。如 Spring 中的 @Repository 是用于扮演仓储角色的模式注解,用来管理和存储某种领域对象。还有如@Component 是通用组件模式、@Service 是服务模式、@Configuration 是配置模式等。其中@Component 作为一种由 Spring 容器托管的通用模式组件,任何被 @Component 标注的组件均为组件扫描的候选对象。类似地,凡是被 @Component 标注的注解,如@Service ,当任何组件标注它时,也被视作组件扫描的候选对象。

举例:

Spring注解 场景说明 起始版本
@Componnt 通用组件模式注解 2.5
@Repository 数据仓储模式注解 2.0
@Service 服务模式注解 2.5
@Controller Web 控制器模式注解 2.5
@Configuration 配置类模式注解 3.0

那么,被这些注解标注的类如何交由Spring来管理呢,或者说如何被Spring所装配呢?接下来我们就来看看Spring的两种装配方式。

2.1、装配方式

  • <context:component-scan> 方式
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd "> <context:component-scan base-package="com.loong.spring.boot" />
</beans>

第一种是XML配置文件的方式,通过 base-package 这个属性指定扫描某个范围内所有被 @Component 或者其派生注解标记的类(Class),将它们注册为 Spring Bean。

我们都知道XML Schema 规范,标签需要显示地关联命名空间,如配置文件中的 xmlns:context="http://www.springframework.org/schema/context" ,且需要与其处理类建立映射关系,而该关系维护在相对于 classpath 下的/META-INF/spring.handlers 文件中。如下:

http\://www.springframework.org/schema/context=org.springframework.context.config.ContextNamespaceHandler
http\://www.springframework.org/schema/jee=org.springframework.ejb.config.JeeNamespaceHandler
http\://www.springframework.org/schema/lang=org.springframework.scripting.config.LangNamespaceHandler
http\://www.springframework.org/schema/task=org.springframework.scheduling.config.TaskNamespaceHandler
http\://www.springframework.org/schema/cache=org.springframework.cache.config.CacheNamespaceHandler

可以看到, context 所对应的处理器为 ContextNamespaceHandler

public class ContextNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
.....
registerBeanDefinitionParser("annotation-config", new AnnotationConfigBeanDefinitionParser());
registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser());
.....
}
}

这里当Spring启动时,init方法被调用,随后注册该命名空间下的所有 Bean 定义解析器,可以看到 <context:component-scan /> 的解析器为 ComponentScanBeanDefinitionParser 。具体的处理过程就在此类中,感兴趣的同学可以去深入了解,这里不再赘述。

  • @ComponentScan 方式
@ComponentScan(basePackages = "com.loong.spring.boot")
public class SpringConfiguration { }

第二种是注解的形式,同样也是依靠 basePackages 属性指定扫描范围。

Spring 在启动时,会在某个生命周期内创建所有的配置类注解解析器,而 @ComponentScan 的处理器为 ComponentScanAnnotationParser ,感兴趣的同学可以去深入了解,这里同样不再赘述。

2.2、派生性

我们用自定义注解的方式来看一看文中提到的派生性:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repository
public @interface FirstLevelRepository {
String value() default "";
}

可以看到我们自定义了一个

@FirstLevelRepository 注解,当前注解又标注了 @Repository,而 @Repository 又标注了 @Component 并且注解属性一致(String value() default""),那么就可以表示当前注解包含了

@Repository 及 @Component 的功能。

派生性其实可以分为多层次的,如

@SprintBootApplication -> @SpringBootConfiguration -> @Configuration -> @Component 可以看到@Component被派生了多个层次,但这种多层次的派生性Spring 4.0版本才开始支持,Spring3.0仅支持两层。

3、Spring @Enable 模块驱动

        前文提到Spring3.X是一个黄金时代,它不仅全面拥抱注解模式,还开始支持“@Enable模块驱动”。所谓“模块”是指具备相同领域的功能组件集合,组合所形成的一个独立的单元,比如 Web MVC 模块、AspectJ代理模块、Caching(缓存)模块、JMX(Java 管理扩展)模块、Async(异步处理)模块等。这种“模块”理念在后续的Spring 、Spring Boot和Spring Cloud版本中都一直被使用,这种模块化的注解均以 @Enable 作为前缀,如下所示:

框架实现 @Enable注解模块 激活模块
Spring Framework @EnableWebMvc Web Mvc 模块
/ @EnableTransactionManagement 事物管理模块
/ @EnableWebFlux Web Flux 模块
Spring Boot @EnableAutoConfiguration 自动装配模块
/ @EnableConfigurationProperties 配置属性绑定模块
/ @EnableOAuth2Sso OAuth2 单点登陆模块
Spring Cloud @EnableEurekaServer Eureka 服务器模块
/ @EnableFeignClients Feign 客户端模块
/ @EnableZuulProxy 服务网关 Zuul 模块
/ @EnableCircuitBreaker 服务熔断模块

引入模块驱动的意义在于简化装配步骤,屏蔽了模块中组件集合装配的细节。但该模式必须手动触发,也就是将该注解标注在某个配置Bean中,同时理解原理和加载机制的成本较高。那么,Spring是如何实现 @Enable 模块呢?主要有以下两种方式。

3.1、Spring框架中@Enable实现方式

  • 基于 @Import 注解

首先,参考 @EnableWebMvc 的实现:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc { } @Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
...
}

这种实现模式主要是通过 @Import 导入配置类 DelegatingWebMvcConfiguration ,而该类标注了 @Configuration 注解,表明这是个配置类,我们都知道 @EnableWebMvc 是用来激活Web MVC模块,所以如HandlerMapping 、HandlerAdapter这些和MVC相关的组件都是在这个配置类中被组装,这也就是所谓的模块理念。

  • 基于接口编程

基于接口编程同样有两种实现方式,第一种参考 @EnableCaching的实现:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(CachingConfigurationSelector.class)
public @interface EnableCaching {
...
} public class CachingConfigurationSelector extends AdviceModeImportSelector<EnableCaching> { @Override
public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) { //switch语句选择实现模式
case PROXY:
return new String[]{AutoProxyRegistrar.class.getName(), ProxyCachingConfiguration.class.getName()};
case ASPECTJ:
return new String[]{AnnotationConfigUtils.CACHE_ASPECT_CONFIGURATION_CLASS_NAME};
default:
}
}
}

这种方式主要是继承 ImportSelector 接口(AdviceModeImportSelector实现了ImportSelector接口),然后实现 selectImports 方法,通过入参进而动态的选择一个或多个类进行导入,相较于注解驱动,此方法更具有弹性。

第二种参考 @EnableApolloConfig 的实现:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ApolloConfigRegistrar.class)
public @interface EnableApolloConfig {
....
}
public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
.... BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class, propertySourcesPlaceholderPropertyValues); BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class.getName(),
PropertySourcesProcessor.class); BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class.getName(),
ApolloAnnotationProcessor.class); BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class.getName(), SpringValueProcessor.class);
BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class.getName(), SpringValueDefinitionProcessor.class); BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloJsonValueProcessor.class.getName(),
ApolloJsonValueProcessor.class);
}
}

这种方式主要是通过 @Import 导入实现了 ImportBeanDefinitionRegistrar 接口的类,在该类中重写 registerBeanDefinitions 方法,通过 BeanDefinitionRegistry 直接手动注册和该模块相关的组件。接下来,我们用这两种方式实现自定义的 @Enable 模块。

3.2、自定义@Enable模块实现

  • 基于 @Import 注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldConfiguration.class)
public @interface EnableHelloWorld {
}
@Configuration
public class HelloWorldConfiguration { // 可以做一些组件初始化的操作。 @Bean
public String helloWorld(){
return "hello world";
}
// ....
}
@EnableHelloWorld
public class EnableHelloWorldBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
.web(WebApplicationType.NONE).run(args);
String helloWorld = context.getBean("helloWorld",String.class);
System.out.println(helloWorld );
}
}

这里我们自定义了一个 @EnableHelloWorld 注解,再用 @Import 导入一个自定义的配置类 HelloWorldConfiguration,在这个配置类中初始化 helloWorld 。

  • 基于接口编程

第一种基于 ImportSelector 接口:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldImportSelector.class)
public @interface EnableHelloWorld {
}
public class HelloWorldImportSelector implements ImportSelector {
/**
* 这种方法比较有弹性:
* 可以调用importingClassMetadata里的方法来进行条件过滤
* 具体哪些方法参考:https://blog.csdn.net/f641385712/article/details/88765470
*/
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
if (importingClassMetadata.hasAnnotation("com.loong.case3.spring.annotation.EnableHelloWorld")) {
return new String[]{HelloWorldConfiguration.class.getName()};
}
}
}
@Configuration
public class HelloWorldConfiguration {
// 可以做一些组件初始化的操作 @Bean
public String helloWorld(){
return "hello world";
}
// ....
}
@EnableHelloWorld
public class EnableHelloWorldBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
.web(WebApplicationType.NONE).run(args);
String helloWorld = context.getBean("helloWorld",String.class);
System.out.println(helloWorld );
}
}

这里我们同样是自定义 @EnableHelloWorld 注解,通过 @Import 导入 HelloWorldImportSelector 类,该类实现了 ImportSelector 接口,在重写的方法中通过 importingClassMetadata.hasAnnotation("com.loong.case3.spring.annotation.EnableHelloWorld") 判断该类是否标注了 @EnableHelloWorld 注解,从而导入 HelloWorldConfiguration 类,进行初始化工作。

第二种基于 ImportBeanDefinitionRegistrar 接口:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldRegistrar.class)
public @interface EnableHelloWorld {
}
public class HelloWorldRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
if (annotationMetadata.hasAnnotation("com.loong..case4.spring.annotation.EnableHelloWorld")) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(HelloWorldConfiguration.class);
beanDefinitionRegistry.registerBeanDefinition(HelloWorldConfiguration.class.getName(), beanDefinition);
}
}
}
@Configuration
public class HelloWorldConfiguration {
public HelloWorldConfiguration() {
System.out.println("HelloWorldConfiguration初始化....");
}
}
@EnableHelloWorld
public class EnableHelloWorldBootstrap {
public static void main(String[] args) {
ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableHelloWorldBootstrap.class)
.web(WebApplicationType.NONE).run(args);
}
}

这里就是在 HelloWorldRegistrar 中利用 BeanDefinitionRegistry 直接注册 HelloWorldConfiguration。

4、Spring 条件装配

        条件装配指的是通过一些列操作判断是否装配 Bean ,也就是 Bean 装配的前置判断。实现方式主要有两种:@Profile 和 @Conditional,这里我们主要讲 @Conditional 的实现方式,因为 @Profile 在 Spring 4.0 后也是通过 @Conditional 来实现。

@Conditional(HelloWorldCondition.class)
@Component
public class HelloWorldConfiguration {
public HelloWorldConditionConfiguration (){
System.out.println("HelloWorldConfiguration初始化。。。");
}
}
public class HelloWorldCondition implements Condition {
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
// ...
return true;
}
}

这里通过自定义一个 HelloWorldConfiguration 配置类,再标注 @Conditional 注解导入 HelloWorldCondition类,该类必须实现 Condition 接口,然后重写 matches 方法,在方法中可以通过两个入参来获取一系列的上下文数据和元数据,最终返回ture或false来判定该类是否初始化,

5、总结

        关于Spring注解驱动的概念就告一段落,最后来简单的回顾下这篇文章的内容,这篇文章主要讲了 Spring 注解相关的几个概念:Spring模式注解、@Enable 模块驱动和 Spring 的条件装配。其中 Spring 模式注解的核心是 @Component,所有的模式注解均被它标注,而对应两种装配方式其实是寻找 @Component 的过程。Spring @Enable 模块的核心是在 @Enable 注解上通过 @Import 导入配置类 ,从而在该配置类中实现和当前模块相关的组件初始化工作。可以看到,Spring 组件装配并不具备自动化,都需要手动标注多种注解,且之间需相互配合,所以下一章我们就来讲讲 Spring Boot是如何基于 Spring 注解驱动来实现自动装配的。

以上就是本章的内容,如过文章中有错误或者需要补充的请及时提出,本人感激不尽。

参考:

《Spring Boot 编程思想》

Spring Boot 自动装配(一)的更多相关文章

  1. Spring Boot 自动装配(二)

    目录 目录 前言 1.起源 2.Spring Boot 自动装配实现 2.1.@EnableAutoConfiguration 实现 2.1.1. 获取默认包扫描路径 2.1.2.获取自动装配的组件 ...

  2. Spring Boot自动装配

    前言 一些朋友问我怎么读源码,这篇文章结合我看源码时候一些思路给大家聊聊,我主要从这三个方向出发: 确定目标,这个目标要是一个具体,不要一上来我要看懂Spring,这是不可能的,目标要这么来定,比如看 ...

  3. Spring Boot自动装配原理源码分析

    1.环境准备 使用IDEA Spring Initializr快速创建一个Spring Boot项目 添加一个Controller类 @RestController public class Hell ...

  4. Spring Boot 自动装配流程

    Spring Boot 自动装配流程 本文以 mybatis-spring-boot-starter 为例简单分析 Spring Boot 的自动装配流程. Spring Boot 发现自动配置类 这 ...

  5. Spring Boot系列(二):Spring Boot自动装配原理解析

    一.Spring Boot整合第三方组件(Redis为例) 1.加依赖 <!--redis--> <dependency> <groupId>org.springf ...

  6. Spring Boot 自动装配原理

    Spring Boot 自动装配原理 Spring Boot 在启动之前还有一系列的准备工作,比如:推断 web 应用类型,设置初始化器,设置监听器,启动各种监听器,准备环境,创建 applicati ...

  7. 深度剖析Spring Boot自动装配机制实现原理

    在前面的分析中,Spring Framework一直在致力于解决一个问题,就是如何让bean的管理变得更简单,如何让开发者尽可能的少关注一些基础化的bean的配置,从而实现自动装配.所以,所谓的自动装 ...

  8. 从源码中理解Spring Boot自动装配原理

    个人博客:槿苏的知识铺 一.什么是自动装配 SpringBoot 定义了一套接口规范,这套规范规定:SpringBoot在启动时会扫描外部引用jar包中的META-INF/spring.factori ...

  9. spring boot 自动装配的原理

    参考: https://blog.csdn.net/Dongguabai/article/details/80865599.如有侵权,请联系本人删除! 入口: import org.springfra ...

随机推荐

  1. Visual Studio Online 的 FAQ:iPad 支持、自托管环境、Web 版 VS Code、Azure 账号等

    北京时间 2019 年 11 月 4 日,在 Microsoft Ignite 2019 大会上,微软正式发布了 Visual Studio Online 公开预览版!发布之后,开发者们都为之振奋.同 ...

  2. Apache配置反向代理、负载均衡和集群(mod_proxy方式)

    Apache配置负载均衡和集群使用mod_jk的方式比较多,但是mod_jk已经停止更新,并且配置相对复杂.Apache2.2以后,提供了一种原生的方式配置负载均衡和集群,比mod_jk简单很多. 1 ...

  3. JVM性能调优详解

    前面我们学习了整个JVM系列,最终目标的不仅仅是了解JVM的基础知识,也是为了进行JVM性能调优做准备.这篇文章带领大家学习JVM性能调优的知识. 性能调优 性能调优包含多个层次,比如:架构调优.代码 ...

  4. 《吊打面试官》系列-Redis终章_凛冬将至、FPX_新王登基

    你知道的越多,你不知道的越多 点赞再看,养成习惯 前言 Redis在互联网技术存储方面使用如此广泛,几乎所有的后端技术面试官都要在Redis的使用和原理方面对小伙伴们进行360°的刁难.作为一个在互联 ...

  5. C++中对封装的语法支持——this指针

    this指针 1.this概念 (1) This指针就是用于成员函数区分调用对象. (2) This指针由编译器自动传递,无须手动传递,函数内部隐藏了this指针参数,本类类型的指针. (3) 编译器 ...

  6. [LC]66题 Plus One (加1)

    ①英文题目 Given a non-empty array of digits representing a non-negative integer, plus one to the integer ...

  7. 【python测试开发栈】python基础语法大盘点

    周边很多同学在用python,但是偶尔会发现有人对python的基础语法还不是特别了解,所以帮大家梳理了python的基础语法(文中的介绍以python3为例).如果你已然是python大牛,可以跳过 ...

  8. nyoj 4 ASCII码排序

    ASCII码排序 时间限制:3000 ms  |  内存限制:65535 KB | 难度:2   描述 输入三个字符(可以重复)后,按各字符的ASCII码从小到大的顺序输出这三个字符.   输入 第一 ...

  9. SQLite性能 - 它不是内存数据库,不要对IN-MEMORY望文生意。

    SQLite创建的数据库有一种模式IN-MEMORY,但是它并不表示SQLite就成了一个内存数据库.IN-MEMORY模式可以简单地理解为,本来创建的数据库文件是基于磁盘的,现在整个文件使用内存空间 ...

  10. NIO流的学习以及Buffer的相关操作

    NIO的使用 一).什么叫NIO? 定义:是一套新的Java I/O标准, 在java1.4中被纳入JDK中. 二).NIO的实现方法 NIO是基于块的, 以块为基本单位处理数据. 标准的I/O是基于 ...