接下来,我们在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