Spring深入淺出(一),HelloWorld程式
一、假設你已經搭建好Spring開發環境,包括:
1. Java 開發工具包,參考:Java SE Downloads
2. Apache Commons Logging API,參考:http://commons.apache.org/logging/
3. MyEclipse2020,參考:https://www.myeclipsecn.com/download/
4. Spring 5.2.3版本,參考:https://repo.spring.io/libs-release-local/org/springframework/spring/5.2.3.RELEASE/spring-5.2.3.RELEASE-dist.zip
並且,至少將下列檔案引用到類庫(MyEclipse中,Build Path -> Configure Build Path):
commons-logging-1.2.jar spring-aop-5.2.3.RELEASE.jar spring-beans-5.2.3.RELEASE.jar spring-context-5.2.3.RELEASE.jar spring-core-5.2.3.RELEASE.jar spring-expression-5.2.3.RELEASE.jar
二、建立HelloWorld程式
1. 建立實體Bean
package com.clzhang.spring.demo; public class HelloWorld { private String message;public void setMessage(String message) { this.message = message; } public void getMessage() { System.out.println("The Message is:" + message); } }
2. 建立呼叫程式
package com.clzhang.spring.demo; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class MainApp { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); HelloWorld objA = (HelloWorld) context.getBean("helloWorld"); objA.getMessage(); } }
3. 建立配置檔案
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="helloWorld" class="com.clzhang.spring.demo.HelloWorld" scope="prototype"> <property name="message" value="Hello World!" /> </bean> </beans>
說明:上面配置檔案中,scope屬性值可以忽略;另外,xmlns:context的註釋也非必要。
4. 執行程式MainApp
The Message is:Hello World!
三、解讀
IoC 容器是 Spring 的核心,也可以稱為 Spring 容器。Spring 提供 2 種不同型別的 IoC 容器,即BeanFactory 和ApplicationContext 容器。BeanFactory 和 ApplicationContext 都是通過 XML 配置檔案載入 Bean 的。
ApplicationContext 繼承了 BeanFactory 介面,由org.springframework.context.ApplicationContext 介面定義,物件在啟動容器時載入。
ApplicationContext 介面有兩個常用的實現類,具體如下:
1)ClassPathXmlApplicationContext
該類從類路徑 ClassPath 中尋找指定的 XML 配置檔案,並完成 ApplicationContext 的例項化工作,具體如下所示:
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(String configLocation);
2)FileSystemXmlApplicationContext
該類從指定的檔案系統路徑中尋找指定的 XML 配置檔案,並完成 ApplicationContext 的例項化工作,具體如下所示:
ApplicationContext applicationContext = new FileSystemXmlApplicationContext(String configLocation);
它與 ClassPathXmlApplicationContext 的區別是:在讀取 Spring 的配置檔案時,FileSystemXmlApplicationContext 不會從類路徑中讀取配置檔案,而是通過引數指定配置檔案的位置。即 FileSystemXmlApplicationContext 可以獲取類路徑之外的資源,如“F:/workspaces/Beans.xml”。
本文參考:
http://c.biancheng.net/spring/ioc.html
https://www.w3cschool.cn/wkspring/dgte1ica.html