傳統 SSH 時代,applicationContext.xml 動輒千行,<bean>、<property>、<constructor-arg> 充斥視野,重構極其痛苦。Spring 2.5+ 引入註解驅動,配合 <context:component-scan>,可實現零 XML 配置 Bean 註冊與注入。
<context:component-scan base-package="com.example" />
掃描指定包及子包下所有帶註解的類,自動註冊為 Spring Bean。屬性微調:
use-default-filters="false" 關閉默認掃描,配合 <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 精確控制base-package 支持多包,逗號分隔| 註解 | 語義層級 | 典型用途 | 元註解 |
|---|---|---|---|
@Component | 通用組件 | 工具類、無明確分層 | @Component |
@Repository | 數據訪問層 | DAO、Mapper 實現 | @Component |
@Service | 業務邏輯層 | Service 實現 | @Component |
@Controller | 表現層 | Spring MVC Controller | @Component |
本質相同:均為 @Component 衍生,僅語義區分,便於 AOP 切面按層攔截(如 execution(* com..service..*(..)))。
@Service @Scope("prototype") // 多例:每次注入創建新實例
public class OrderService { ... }
@Controller @Scope("request") // Web 請求級(需 Web 環境)
public class FormController { ... }
默認 singleton(單例),有狀態 Bean 必須聲明 prototype/request/session,否則併發安全隱患極大。
| 註解 | 來源 | 匹配規則 | 推薦場景 |
|---|---|---|---|
@Autowired | Spring | 1. byType 2. @Qualifier 指定 name 3. 字段名作為 fallback | 構造器注入(強制依賴) |
@Resource | JSR-250 | 1. byName 2. byType | 字段/Setter 注入,名稱穩定時 |
@Inject | JSR-330 | 同 @Autowired,無 required 屬性 | 標準化項目 |
優勢:不可變、不可為 null、易測試(無需 Spring 容器)、循環依賴啟動時報錯。
// 1. 實現 Converter
@Component
public class StringToLocalDateConverter implements Converter<String, LocalDate> {
@Override public LocalDate convert(String source) {
return LocalDate.parse(source, DateTimeFormatter.ISO_LOCAL_DATE);
}
}
// 2. 註冊到 FormattingConversionService
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToLocalDateConverter());
}
}
之後 Controller 參數 @RequestParam LocalDate date 自動轉換。
<bean> 定義@Component/@Service/@Repository/@Controller<property ref=...> 改為 @Autowired/@Resource 構造器注入<context:component-scan> 覆蓋項目根包web 包,Service 在 service 包,base-package 僅掃描 service → Controller 未註冊 → 404ObjectFactory<T> 或 @Lookup 方法注入註解驅動將配置從「外部 XML」遷移到「代碼內部」,實現配置即代碼、代碼即文檔。核心三步:component-scan 掃描、類級註解分層、構造器注入賦值。配合 @Configuration + @Bean 處理第三方庫,可實現 95%+ 場景零 XML。