首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 實戰精髓(14):@ComponentScan 自動掃描與組件過濾完全指南

     編輯:Java 綜合教學

Spring 實戰精髓(14):@ComponentScan 自動掃描與組件過濾完全指南

<context:component-scan> 是 Spring 實現「約定優於配置」的核心基礎設施。它不僅包含 <context:annotation-config> 的注解處理能力(@Autowired、@Resource、@PostConstruct 等),更能自動發現並註冊 Bean,徹底擺脫 XML 顯式 <bean> 定義的繁瑣。

基礎配置:啟用掃描

<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="... spring-context.xsd">

    <context:component-scan base-package="com.example" />
</beans>
  • base-package:掃描起始包(含子包),多包用逗號/分號/空格分隔。
  • 掃描目標:標註構造型注解 的類。

四大核心構造型注解

注解語義層級典型用途備註
@Component通用組件無法歸類的通用 Bean元注解,其他三者均繼承此注解
@Repository持久層DAO、Mapper自動轉換 JDBC/Hibernate 異常為 DataAccessException
@Service業務層Service、Manager標識業務邏輯組件,便於 AOP 切面匹配
@Controller表現層Spring MVC ControllerDispatcherServlet 會自動識別並註冊 HandlerMapping

Bean 名稱生成規則

  • 默認:非限定類名首字母小寫(School → school)。
  • 自定義:@Component("myBeanName") 或 @Service("orderService")。
  • 實現 BeanNameGenerator 接口並配置 name-generator 屬性,全局自定義命名策略。

進階:組件過濾器——精準控制掃描範圍

默認掃描所有構造型注解類,但實際項目常需「只掃描特定接口實現」或「排除特定模組」。通過 <context:include-filter> 與 <context:exclude-filter> 實現。

五種過濾器類型

typeexpression 示例匹配邏輯
annotationorg.springframework.stereotype.Service類上標註指定注解
assignablecom.example.dao.BaseDao類實現/繼承指定類/介面(isAssignableFrom)
aspectjcom.example..*Service+AspectJ 類型模式表達式
regexcom\.example\..*Impl類全限定名匹配正則
customcom.example.MyTypeFilter實現 TypeFilter 接口的自定義邏輯

實戰案例:只註冊實現 Worker 介面的類,排除 Performer 實現

<context:component-scan base-package="com.example">
    <context:include-filter type="assignable" expression="com.example.Worker" />
    <context:exclude-filter type="assignable" expression="com.example.Performer" />
</context:component-scan>

驗證:

Farmer farmer = ctx.getBean("farmer", Farmer.class); // 成功,實現 Worker
farmer.work(); // "正在辛勤的耕地..."

Singer singer = ctx.getBean("singer", Singer.class); // 拋出 NoSuchBeanDefinitionException
// 實現 Performer 被 exclude-filter 排除

過濾器優先級規則

  1. exclude-filter 優先於 include-filter(排除勝出)。
  2. 多個同類型過濾器按聲明順序疊加。
  3. 默認隱含 include-filter type="annotation" expression="Component,Repository,Service,Controller"。
  4. 使用 use-default-filters="false" 可禁用默認注解掃描,完全自定義策略。

最佳實踐建議

  • 分層掃描:Web 層掃描 controller 包,Service 層掃描 service 包,避免重複掃描導致 Bean 衝突。
  • 排除測試代碼:exclude-filter type="regex" expression=".*\.test\..*"。
  • Spring Boot 時代:@SpringBootApplication 默認掃描啟動類同級及子包,通常無需額外配置;複雜場景用 @ComponentScan 微調。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved