使用@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