前言
在实际工作中。普遍都是使用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