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的功能。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM