3. @ComponentScan 注解自动扫描和指定扫描规则

398 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第2天,点击查看活动详情

1. xml文件自动扫描

1.1 使用 XML 文件配置包扫描

首先在 beanconfig.xml 文件中增加扫描

 <context:component-scan base-package="com.shanggushenlong"></context:component-scan>

意思:包扫描,只要是标注了 @Controller @Service @Repository @Component 这几个注解,就都会被认为是组件,当项目启动的时候,spring就会自动去扫描 base-package 这个文件夹及其子目录下所有的类,并且加入容器中去

注意:如果xml文件要能使用 <context:component-scan> 那么需要增加节点 xmlns:context="http://www.springframework.org/schema/context

1.2 增加类文件,添加注解

image.png

1.2 测试

    @Test
    public void testBean03() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beanconfig.xml");
        
        // 查看当前容器中有哪些 bean, (查看所有 bean的名字)
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();

        for (String beanName : beanDefinitionNames) {
            System.out.println("beanName = " + beanName);

        }
    }

image (1).png

spring扫描到了刚刚手动创建的类,并且还扫描到了 Spring 启动所需要的自身的一些 bean 的内部类

2. 使用 @ComponentScan 注解配置包扫描

2.1 先增加注解

首先注释前面在 beanconfig.xml 文件中添加的 <context:component-scan> , 然后在 MainBeanConfig 类上添加注解 @Component 注解,并且指定扫描的包。

// value 指定扫描的包路径
@ComponentScan(value = {"com.shanggushenlong"})
@Configuration
public class MainBeanConfig {

    @Bean(value = {"person01"})
    public Person person() {
        return new Person("张三", 28);
    }
}

2.2 测试

    @Test
    public void testBean04() {
        // 通过 AnnotationConfigApplicationContext 获取注解类,通过注解获取容器
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainBeanConfig.class);

        // 获取容器中所有的 bean
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanDefinitionNames) {
            System.out.println("beanName = " + beanName);
        }
    }

能够正常的获取扫描到。 注意:此时应该使用 AnnotationConfigApplicationContext 获取注解配置类

image (2).png

3. @Component 新属性用法

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
// 表示可重复使用组件
@Repeatable(ComponentScans.class) 
public @interface ComponentScan {
    
    // 包含哪些
    Filter[] includeFilters() default {};
    
    // 排除哪些
    Filter[] excludeFilters() default {};
}

includeFilters() 方法指定Spring扫描的时候按照什么规则只需要包含哪些组件

excludeFilters() 方法指定Spring扫描的时候按照什么规则排除哪些组件