百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术教程 > 正文

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

suiw9 2025-03-14 20:30 10 浏览 0 评论

目录

  • 前言
  • 1、起源
  • 2、Spring 模式注解
  • 2.1、装配方式context:component-scan 方式@ComponentScan 方式
  • 2.2、派生性
  • 3、Spring @Enable 模块驱动
  • 3.1、Spring框架中@Enable实现方式基于 @Import 注解基于接口编程
  • 3.2、自定义@Enable模块实现基于 @Import 注解基于接口编程
  • 4、Spring 条件装配
  • 5、总结

前言

开始之前呢,希望大家带着几个问题去学习: 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

@Service

服务模式注解

2.5

@Controller

Web 控制器模式注解

2.5

@Configuration

配置类模式注解

3

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

2.1、装配方式

  • context:component-scan 方式



    

第一种是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 定义解析器,可以看到 的解析器为
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

自动装配模块

/

@EnableOAuth2Sso

OAuth2 单点登陆模块

/

@EnableConfigurationProperties

配置属性绑定模块

Spring Cloud

@EnableEurekaServer

Eureka 服务器模块

/

@EnableFeignClients

Feign 客户端模块

/

@EnableZuulProxy

服务网关 Zuul 模块

/

@EnableCircuitBreaker

服务熔断模块

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

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

3.1.1 基于 @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相关的组件都是在这个配置类中被组装,这也就是所谓的模块理念。

3.1.2 基于ImportSelector接口编程

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

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(CachingConfigurationSelector.class)
public @interface EnableCaching {
    ...
}

public class CachingConfigurationSelector extends AdviceModeImportSelector {

    @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 方法,通过入参进而动态的选择一个或多个类进行导入,相较于注解驱动,此方法更具有弹性。

3.1.3 基于ImportBeanDefinitionRegistrar接口

第二种参考 @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 注解和@Configuration配置类
@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 注解驱动来实现自动装配的。

相关推荐

俄罗斯的 HTTPS 也要被废了?(俄罗斯网站关闭)

发布该推文的ScottHelme是一名黑客,SecurityHeaders和ReportUri的创始人、Pluralsight作者、BBC常驻黑客。他表示,CAs现在似乎正在停止为俄罗斯域名颁发...

如何强制所有流量使用 HTTPS一网上用户

如何强制所有流量使用HTTPS一网上用户使用.htaccess强制流量到https的最常见方法可能是使用.htaccess重定向请求。.htaccess是一个简单的文本文件,简称为“.h...

https和http的区别(https和http有何区别)

“HTTPS和HTTP都是数据传输的应用层协议,区别在于HTTPS比HTTP安全”。区别在哪里,我们接着往下看:...

快码住!带你十分钟搞懂HTTP与HTTPS协议及请求的区别

什么是协议?网络协议是计算机之间为了实现网络通信从而达成的一种“约定”或“规则”,正是因为这个“规则”的存在,不同厂商的生产设备、及不同操作系统组成的计算机之间,才可以实现通信。简单来说,计算机与网络...

简述HTTPS工作原理(简述https原理,以及与http的区别)

https是在http协议的基础上加了一层SSL(由网景公司开发),加密由ssl实现,它的目的是为用户提供对网站服务器的身份认证(需要CA),以至于保护交换数据的隐私和完整性,原理如图示。1、客户端发...

21、HTTPS 有几次握手和挥手?HTTPS 的原理什么是(高薪 常问)

HTTPS是3次握手和4次挥手,和HTTP是一样的。HTTPS的原理...

一次安全可靠的通信——HTTPS原理

为什么HTTPS协议就比HTTP安全呢?一次安全可靠的通信应该包含什么东西呢,这篇文章我会尝试讲清楚这些细节。Alice与Bob的通信...

为什么有的网站没有使用https(为什么有的网站点不开)

有的网站没有使用HTTPS的原因可能涉及多个方面,以下是.com、.top域名的一些见解:服务器性能限制:HTTPS使用公钥加密和私钥解密技术,这要求服务器具备足够的计算能力来处理加解密操作。如果服务...

HTTPS是什么?加密原理和证书。SSL/TLS握手过程

秘钥的产生过程非对称加密...

图解HTTPS「转」(图解http 完整版 彩色版 pdf)

我们都知道HTTPS能够加密信息,以免敏感信息被第三方获取。所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用HTTPS协议。...

HTTP 和 HTTPS 有何不同?一文带你全面了解

随着互联网时代的高速发展,Web服务器和客户端之间的安全通信需求也越来越高。HTTP和HTTPS是两种广泛使用的Web通信协议。本文将介绍HTTP和HTTPS的区别,并探讨为什么HTTPS已成为We...

HTTP与HTTPS的区别,详细介绍(http与https有什么区别)

HTTP与HTTPS介绍超文本传输协议HTTP协议被用于在Web浏览器和网站服务器之间传递信息,HTTP协议以明文方式发送内容,不提供任何方式的数据加密,如果攻击者截取了Web浏览器和网站服务器之间的...

一文让你轻松掌握 HTTPS(https详解)

一文让你轻松掌握HTTPS原文作者:UC国际研发泽原写在最前:欢迎你来到“UC国际技术”公众号,我们将为大家提供与客户端、服务端、算法、测试、数据、前端等相关的高质量技术文章,不限于原创与翻译。...

如何在Spring Boot应用程序上启用HTTPS?

HTTPS是HTTP的安全版本,旨在提供传输层安全性(TLS)[安全套接字层(SSL)的后继产品],这是地址栏中的挂锁图标,用于在Web服务器和浏览器之间建立加密连接。HTTPS加密每个数据包以安全方...

一文彻底搞明白Http以及Https(http0)

早期以信息发布为主的Web1.0时代,HTTP已可以满足绝大部分需要。证书费用、服务器的计算资源都比较昂贵,作为HTTP安全扩展的HTTPS,通常只应用在登录、交易等少数环境中。但随着越来越多的重要...

取消回复欢迎 发表评论: