Spring系列11:@ComponentScan批量注册bean

本文详细介绍了Spring的@ComponentScan注解,包括其基本原理、使用案例、进阶功能如Filters过滤、自定义bean名称生成策略和作用域策略。还探讨了@Component及其衍生注解的使用,以及元注解和组合注解的概念。
摘要由CSDN通过智能技术生成

回顾

在前面的章节,我们介绍了@Comfiguration@Bean结合AnnotationConfigApplicationContext零xml配置文件使用Spring容器的方式,也介绍了通过<context:component-scan base-package="org.example"/>扫描包路径下的bean的方式。如果忘了可以看下前面几篇。这篇我们来结合这2种方式来理解@ComponentScan

本文内容

  1. @ComponentScan基本原理和使用

  2. @ComponentScan进阶使用

  3. @Componet及其衍生注解使用

@ComponentScan基本原理和使用

基本原理

源码中解析为配置组件扫描指令与@Configuration类一起使用提供与 Spring XML 的 <context:component-scan> 元素同样的作用支持。简单点说,就是可以扫描特定包下的bean定义信息,将其注册到容器中,并自动提供依赖注入。

@ComponentScan可以对应一下xml配置。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="org.example"/>

</beans>

提示: 使用 <context:component-scan> 隐式启用 <context:annotation-config> 的功能,也就是扫描批量注册并自动DI。

默认情况下,使用@Component@Repository@Service@Controller@Configuration 注释的类或本身使用@Component 注释的自定义注释是会作为组件被@ComponentScan指定批量扫描到容器中自动注册。

使用案例
定义组件
@Component
public class RepositoryA implements RepositoryBase {
}

@Component
public class Service1 {
    @Autowired
    private RepositoryBase repository;
}
定义配置类
@Configuration
@ComponentScan(basePackages = "com.crab.spring.ioc.demo08")
public class AppConfig {
}
容器扫描和使用
    @org.junit.Test
    public void test_comp
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值