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

Spring JavaConfig 完整指南:從 XML 到註解式配置的遷移

     編輯:Java 綜合教學

緣起與背景

隨著 Java 5 帶來註解特性,以及 Google Guice 等純 Java 依賴注入框架的出現,Spring 推出了 JavaConfig 專案,提供基於 Java 程式碼與註解的配置方式,逐步取代傳統冗長的 XML 配置。JavaConfig 不僅類型安全、支援 IDE 重構,更能充分發揮 Java 語言的表達能力。

一、配置類的基本形式

傳統 XML 配置

<?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>

JavaConfig 等效寫法

@Configuration
public class AppConfig {
    // bean 定義方法
}

任何標註 @Configuration 的類別即為一個 JavaConfig 配置類,相當於一個 <beans> XML 檔案。

二、Bean 註冊方式對照

1. 單一 Bean 定義

XMLJavaConfig
<bean id="mockService" class="...MockServiceImpl">
  ...
</bean>
@Configuration
public class AppConfig {
    @Bean
    public MockService mockService() {
        return new MockServiceImpl();
    }
}

@Bean 方法的回傳值將註冊為 Bean,方法名預設為 Bean ID。

2. 批量掃描註冊(Component Scan)

XMLJavaConfig
<context:component-scan base-package="com.example"/>
@ComponentScan(basePackages = "com.example")

@ComponentScan 是 Spring Boot 自動配置的核心組件之一,支援多套基礎套件路徑。

三、依賴注入關係表達

XML 方式

<bean id="mockService" class="...MockServiceImpl">
    <property name="dependencyService" ref="dependencyService"/>
</bean>
<bean id="dependencyService" class="...DependencyServiceImpl"/>

JavaConfig 方式

@Configuration
public class AppConfig {
    @Bean
    public MockService mockService() {
        // 直接呼叫同配置類內的另一個 @Bean 方法
        return new MockServiceImpl(dependencyService());
    }

    @Bean
    public DependencyService dependencyService() {
        return new DependencyServiceImpl();
    }
}

關鍵優勢:依賴關係在程式碼中以強類型方法呼叫呈現,編譯期即可檢查,避免 XML 中拼寫錯誤的 ref 屬性值導致啟動失敗。

四、進階技巧

  • @Import:組合多個配置類,@Import({DbConfig.class, SecurityConfig.class})
  • @Profile:環境隔離,@Profile("dev") / @Profile("prod")
  • @PropertySource:載入外部屬性檔,@PropertySource("classpath:app.properties")
  • @Enable* 模組啟用註解:如 @EnableTransactionManagement、@EnableCaching 等

總結

JavaConfig 以類型安全、程式碼即文檔、易於重構等優勢,已成為現代 Spring 應用的主流配置方式。Spring Boot 更進一步將其作為預設配置模型,搭配自動配置機制,極大簡化了專案啟動與維護成本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved