隨著 Java 5 帶來註解特性,以及 Google Guice 等純 Java 依賴注入框架的出現,Spring 推出了 JavaConfig 專案,提供基於 Java 程式碼與註解的配置方式,逐步取代傳統冗長的 XML 配置。JavaConfig 不僅類型安全、支援 IDE 重構,更能充分發揮 Java 語言的表達能力。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean 定義 -->
</beans>
@Configuration
public class AppConfig {
// bean 定義方法
}
任何標註 @Configuration 的類別即為一個 JavaConfig 配置類,相當於一個 <beans> XML 檔案。
| XML | JavaConfig |
|---|---|
|
|
@Bean 方法的回傳值將註冊為 Bean,方法名預設為 Bean ID。
| XML | JavaConfig |
|---|---|
|
|
@ComponentScan 是 Spring Boot 自動配置的核心組件之一,支援多套基礎套件路徑。
<bean id="mockService" class="...MockServiceImpl">
<property name="dependencyService" ref="dependencyService"/>
</bean>
<bean id="dependencyService" class="...DependencyServiceImpl"/>
@Configuration
public class AppConfig {
@Bean
public MockService mockService() {
// 直接呼叫同配置類內的另一個 @Bean 方法
return new MockServiceImpl(dependencyService());
}
@Bean
public DependencyService dependencyService() {
return new DependencyServiceImpl();
}
}
關鍵優勢:依賴關係在程式碼中以強類型方法呼叫呈現,編譯期即可檢查,避免 XML 中拼寫錯誤的 ref 屬性值導致啟動失敗。
@Import({DbConfig.class, SecurityConfig.class})@Profile("dev") / @Profile("prod")@PropertySource("classpath:app.properties")@EnableTransactionManagement、@EnableCaching 等JavaConfig 以類型安全、程式碼即文檔、易於重構等優勢,已成為現代 Spring 應用的主流配置方式。Spring Boot 更進一步將其作為預設配置模型,搭配自動配置機制,極大簡化了專案啟動與維護成本。