一篇文章带你弄懂【Spring Boot】自动扫描组件

本文详细介绍了Spring Boot的自动扫描组件功能,包括@Componentscan的使用,如何指定扫描包,排除过滤规则,以及使用spring.factories加载第三方bean。通过实例展示了如何配置和自定义扫描规则,以及解决Spring Boot无法扫描到非默认路径下Bean的问题。
摘要由CSDN通过智能技术生成

使用@componentscan自动扫描组件

案例准备

1.创建一个配置类,在配置类上添加@ComponentScan注解。该注解默认会扫描该类所在的包下所有的配置类,相当于之前的context:component-scan

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class BeanConfig {
   

}

2.使用 ApplicationContext 的 getBeanDefinitionNames() 方法获取已经注册到容器中的 bean 的名称。

import io.mieux.config.BeanConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class App02 {
   
    public static void main(String[] args) {
   
        ApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(BeanConfig.class);

        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanDefinitionNames) {
   
            System.out.println("beanName: " + beanName);
        }
    }
}

运行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event.internalEventListenerFactory
beanName: beanConfig

除了 spring 本身注册的一些 bean 之外,可以看到最后一行,已经将BeanConfig这个类注册进容器中了。

使用@componentscan的valule属性配置

3.指定要扫描的包(使用@ComponentScan 的 valule 属性来配置)

创建一个controller 包,并在该包下新建一个 AppController 类。

package io.mieux.controller;

import org.springframework.stereotype.Controller;

@Controller
public class AppController {
   
}

在类上加了@Controller注解,说明该类是一个 Component。在 BeanConfig 类中修改:

package io.mieux.config;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan(value = "io.mieux.controller")
public class BeanConfig {
   

}

在 @ComponentScan 注解中指定了要扫描的包。

运行效果:

beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor
beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalRequiredAnnotationProcessor
beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor
beanName: org.springframework.context.event.internalEventListenerProcessor
beanName: org.springframework.context.event
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值