spring应用手册-IOC(注解实现)-(23)-@ComponentScan和@ComponentScans注解

    科技2026-10-01  7

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

    @ComponentScan和@ComponentScans注解

    spring应用手册(第二部分)

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

    简单案例如下:

    /** * @author 戴着假发的程序员 * * @description */ @Configuration @ComponentScan("com. st.dk.demo4") public class AppConfig { }

    或者

    /** * @author 戴着假发的程序员 * * @description */ @Configuration @ComponentScan({"com. st.dk.demo4","com. st.dk.otherpk"}) public class AppConfig { }

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

    @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented public @interface ComponentScans { ComponentScan[] value(); }

    我们可以这样配置:

    /** * @author 戴着假发的程序员 */ @Configuration @ComponentScans({ @ComponentScan("com.st.demo1"), @ComponentScan("com.st") }) public class AppConfig { }

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

    @Test public void testComponentScan(){ ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); }

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

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

    例如:

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

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

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