SpringBoot(一)自动装配基础 - @Component、@ComponentScan、@Enable 模块

前言

        最近在学习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 编程思想》

posted @ 2019-12-02 13:58  龙四丶  阅读(10291)  评论(1编辑  收藏  举报