Spring注解驱动开发第3和第4讲——使用@ComponentScan注解自动扫描组件and指定扫描规则(或自定义扫描规则)

本文详细讲解了Spring包扫描的两种配置方式,包括XML配置和@ComponentScan注解,并重点介绍如何利用@ComponentScan注解自定义扫描规则,以及如何通过TypeFilter实现按特定条件注入组件。此外,还探讨了如何使用excludeFilters排除特定注解的组件和设置多扫描规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

在实际工作中。普遍都是使用Spring的扫描包功能对项目中的包进行扫描,凡是在指定的包或其子包中的类上标注了@Repository(通常用于DAO层)、@Service(通常作用在业务层)、@Controller(通常作用在控制层)、@Component(可以自定义用哪里,没有限制)注解的类都会被扫描到,并将这些类注入到Spring容器中。目前这四个注解的功能是完全一样的。

Spring包扫描功能可以使用【XML配置文件】进行配置,也可以直接使用【@ComponentScan注解】进行设置,使用 @ComponentScan注解进行设置比使用XML配置文件来配置要简单的多。

一、使用XML文件配置包扫描

1、需要在Spring的XML配置文件中的beans标签中引入context属性,如下所示。

在这里插入图片描述
完整代码

<?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
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/context
            https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 包扫描:只要是标注了我们熟悉的
    @Controller、@Service、@Repository、@Component
    这四个注解中的任何一个的组件,它就会被自动扫描,并加进容器中 
    -->
    <context:component-scan base-package="com.leo"></context:component-scan>
</beans>

2、验证代码效果,

a、创建四个类型,分别使用这四个注解来验证效果
在这里插入图片描述
b、使用的是junit来进行测试(在测试方法上加上注解@Test即可),因此还须在pom.xml文件中添加对junit的依赖,如下所示。

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

c、查看spingIOC容器中有是否有我们指定注入的组件
在这里插入图片描述

细节:配置类(MainConfig.java)为什么也被注入springIOC容器中?因为配置类注解 @Configuration 也用到了注解 @Component 。
在这里插入图片描述

二、使用扫描注解配置包扫描

1、在配置类上添加注解@ComponentScan(value = “com.leo”),value属性写明需要扫描的包

在这里插入图片描述

2、验证效果

在这里插入图片描述

三、注解@ComponentScan 指定扫描规则(指定注入springIOC容器的规则)

1、先看看注解@ComponentScan源码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.context.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值