<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 Controller | DispatcherServlet 會自動識別並註冊 HandlerMapping |
School → school)。@Component("myBeanName") 或 @Service("orderService")。BeanNameGenerator 接口並配置 name-generator 屬性,全局自定義命名策略。默認掃描所有構造型注解類,但實際項目常需「只掃描特定接口實現」或「排除特定模組」。通過 <context:include-filter> 與 <context:exclude-filter> 實現。
| type | expression 示例 | 匹配邏輯 |
|---|---|---|
annotation | org.springframework.stereotype.Service | 類上標註指定注解 |
assignable | com.example.dao.BaseDao | 類實現/繼承指定類/介面(isAssignableFrom) |
aspectj | com.example..*Service+ | AspectJ 類型模式表達式 |
regex | com\.example\..*Impl | 類全限定名匹配正則 |
custom | com.example.MyTypeFilter | 實現 TypeFilter 接口的自定義邏輯 |
<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 排除
exclude-filter 優先於 include-filter(排除勝出)。include-filter type="annotation" expression="Component,Repository,Service,Controller"。use-default-filters="false" 可禁用默認注解掃描,完全自定義策略。controller 包,Service 層掃描 service 包,避免重複掃描導致 Bean 衝突。exclude-filter type="regex" expression=".*\.test\..*"。@SpringBootApplication 默認掃描啟動類同級及子包,通常無需額外配置;複雜場景用 @ComponentScan 微調。