2.23@ComponentScan和@ComponentScans注解

戴着假发的程序员出品  抖音ID:戴着假发的程序员  欢迎关注

[查看视频教程]

@ComponentScan往往是注解在@Configuration的类中,用于添加自动扫描的包。我们可以通过属性basePackages或者value指定一个或者多个要扫描的包。

简单案例如下:

1 /**
2  * @author 戴着假发的程序员
3  *  
4  * @description
5  */
6 @Configuration
7 @ComponentScan("com. st.dk.demo4")
8 public class AppConfig {
9 }

或者

1 /**
2  * @author 戴着假发的程序员
3  *  
4  * @description
5  */
6 @Configuration
7 @ComponentScan({"com. st.dk.demo4","com. st.dk.otherpk"})
8 public class AppConfig {
9 }

@ComponentScans是另外一个扫描包的注解,有一个数组形势的属性value,而数组的类型就是@ComponentScan,也就是一个@ComponentScans中可以配置多个@ComponentScan

1 @Retention(RetentionPolicy.RUNTIME)
2 @Target(ElementType.TYPE)
3 @Documented
4 public @interface ComponentScans {
5    ComponentScan[] value();
6 }

我们可以这样配置:

 1 /**
 2  * @author 戴着假发的程序员
 3  */
 4 @Configuration
 5 @ComponentScans({
 6         @ComponentScan("com.st.demo1"),
 7         @ComponentScan("com.st")
 8 })
 9 public class AppConfig {
10 }

这时我们创建容器的方式应该是下面的方式:

1 @Test
2 public void testComponentScan(){
3     ApplicationContext ac =
4             new AnnotationConfigApplicationContext(AppConfig.class);
5 }

spring会扫描所有ComponentScan指定的包以及他们的子孙包中所有的类。

当然同样的我们其实可以在配置文件中使用context:component-scan标签配置扫描的包。

例如:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans
 6         http://www.springframework.org/schema/beans/spring-beans.xsd
 7         http://www.springframework.org/schema/context
 8         http://www.springframework.org/schema/context/spring-context.xsd">
 9     <context:component-scan base-package="com. st.dk.demo"/>
10 </beans>

这里要注意,如果要使用context需要引入对应的namespace。

通常情况下context:component-scan标签会隐式启用context:annotation-config的功能。

 

posted @ 2020-10-12 08:25  戴着假发的程序员0-1  阅读(3322)  评论(0编辑  收藏  举报