【Spring注解驱动开发】使用@ComponentScan自动扫描组件并指定扫描规则(1)

按照上面的过程,4个月的时间刚刚好。当然Java的体系是很庞大的,还有很多更高级的技能需要掌握,但不要着急,这些完全可以放到以后工作中边用别学。学习编程就是一个由混沌到有序的过程,所以你在学习过程中,如果一时碰到理解不了的知识点,大可不必沮丧,更不要气馁,这都是正常的不能再正常的事情了,不过是“人同此心,心同此理”的暂时而已。道路是曲折的,前途是光明的!《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!发知识点,真正体系化!**
摘要由CSDN通过智能技术生成

接下来,我们在SpringBeanTest类中新建一个测试方法testComponentScanByXml()进行测试,如下所示。

@Test

public void testComponentScanByXml(){

ApplicationContext context = new ClassPathXmlApplicationContext(“beans.xml”);

String[] names = context.getBeanDefinitionNames();

Arrays.stream(names).forEach(System.out::println);

}

运行测试用例,输出的结果信息如下所示。

personConfig

personController

personDao

personService

org.springframework.context.annotation.internalConfigurationAnnotationProcessor

org.springframework.context.annotation.internalAutowiredAnnotationProcessor

org.springframework.context.annotation.internalCommonAnnotationProcessor

org.springframework.context.event.internalEventListenerProcessor

org.springframework.context.event.internalEventListenerFactory

person

可以看到,除了输出我们自己创建的bean名称之外,也输出了Spring内部使用的一些重要的bean名称。

接下来,我们使用注解来完成这些功能。

使用注解配置包扫描


使用@ComponentScan注解之前我们先将beans.xml文件中的下述配置注释。

<context:component-scan base-package=“io.mykit.spring”></context:component-scan>

注释后如下所示。

使用@ComponentScan注解配置包扫描就非常Easy了!在我们的PersonConfig类上添加@ComponentScan注解,并将扫描的包指定为io.mykit.spring即可,整个的PersonConfig类如下所示。

package io.mykit.spring.plugins.register.config;

import io.mykit.spring.bean.Person;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

/**

  • @author binghe

  • @version 1.0.0

  • @description 以注解的形式来配置Person

*/

@Configuration

@ComponentScan(value = “io.mykit.spring”)

public class PersonConfig {

@Bean(“person”)

public Person person01(){

return new Person(“binghe001”, 18);

}

}

没错,就是这么简单,只需要在类上添加@ComponentScan(value = “io.mykit.spring”)注解即可。

接下来,我们在SpringBeanTest类中新增testComponentScanByAnnotation()方法,如下所示。

@Test

public void testComponentScanByAnnotation(){

ApplicationContext context = new AnnotationConfigApplicationContext(PersonConfig.class);

String[] names = context.getBeanDefinitionNames();

Arrays.stream(names).forEach(System.out::println);

}

运行testComponentScanByAnnotation()方法输出的结果信息如下所示。

org.springframework.context.annotation.internalConfigurationAnnotationPro

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值