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

Spring 入門第一課:IoC 容器管理 Bean 的 HelloWorld 實戰

     編輯:Java 綜合教學

Spring 入門第一課:IoC 容器管理 Bean 的 HelloWorld 實戰

Spring 核心是控制反轉 (IoC) 容器,負責建立、管理 Bean 生命週期與依賴關係。本文通過最簡單的 HelloWorld 案例,揭示「工廠模式」如何取代傳統 new 方式,降低耦合度。

專案結構

src/
├─ com.qinb.service
│  └─ HelloWorld.java
├─ beans.xml
└─ Test.java

專案結構圖

核心配置 beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
       xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="https://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 相當於實例化 HelloWorld 類 -->
    <bean id="helloWorld" class="com.qinb.service.HelloWorld" />

</beans>

關鍵點: id 為 Bean 唯一標識,class 指定全限定類名。慣例 id 使用駝峰首字母小寫。

業務類 HelloWorld

package com.qinb.service;

public class HelloWorld {
    public void say() {
        System.out.println("Hello, Spring IoC!");
    }
}

HelloWorld 類代碼

測試類:從容器獲取 Bean

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.qinb.service.HelloWorld;

public class Test {
    public static void main(String[] args) {
        // 1. 啟動容器,載入配置
        ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
        // 2. 依 id 獲取 Bean(注意大小寫)
        HelloWorld hw = (HelloWorld) ac.getBean("helloWorld");
        // 3. 呼叫業務方法
        hw.say();
    }
}

運行結果

控制台輸出 Hello, Spring IoC!

核心概念對比

傳統方式Spring IoC 方式
調用方 new HelloWorld()容器負責實例化,調用方僅獲取
依賴具體實現類依賴抽象/介面,實現類可替換
物件生命週期自管容器統一管理(單例、原型、初始化/銷毀回調)

比喻: 傳統方式像「餓了自己做筷子」,Spring 像「筷子備好放抽屜,需要時直接拿」。統一管理、按需獲取,大型專案中極大降低維護成本。

延伸學習路徑

  1. 依賴注入 (DI):setter 注入、建構子注入、@Autowired 註解注入。
  2. Bean 作用域:singleton、prototype、request、session。
  3. 生命週期回調:InitializingBean、DisposableBean、@PostConstruct/@PreDestroy。
  4. 註解配置:@Component、@Configuration、@Bean 取代 XML。

掌握 IoC 容器運作機制,是精通 Spring 生態的基石。

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