javascript
Spring的HelloWorld
Spring模塊:
使用 Eclipse 開發(fā),要先安裝 Spring Tool Suite。
安裝過程中,只勾選 Spring IDE 結(jié)尾(4個)的即可,并把聯(lián)網(wǎng)進行更新去掉(否則聯(lián)網(wǎng)速度會變慢)。
?
開發(fā)步驟:
1. 加入jar包(5個)
?
?
2. 創(chuàng)建一個 javaBean 類
package cn.jmu.spring.beans;public class HelloWorld {private String name;public void setName(String name) {System.out.println("setName 方法執(zhí)行...setName: " + name);this.name = name;}public void hello(){System.out.println("Hello: " + name);}/** 構(gòu)造函數(shù),用來查看該類的對象是什么時候創(chuàng)建的*/public HelloWorld(){System.out.println("HelloWorld 對象創(chuàng)建...");} }?
3. 在src下新建一個 Spring Bean Configuration file 文件,一般命名為:applicationContext.xml ,在這個文件中配置 bean。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 配置 bean --><bean id="helloWorld" class="cn.jmu.spring.beans.HelloWorld"> <!-- 這里其實是使用了反射來創(chuàng)建一個對象。 --><!-- 為 HelloWorld 類的 name 屬性賦值,即會執(zhí)行 HelloWorld 的 setName方法 --><property name="name" value="Sky"></property></bean></beans>?
4. 使用 IOC 容器創(chuàng)建對象和調(diào)用對象的方法。
package cn.jmu.spring.beans;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {/** 傳統(tǒng)方法* HelloWorld helloWorld = new HelloWorld();* helloWorld.setName("Sky");* helloWorld.hello();*///1. 創(chuàng)建 Spring 的 IOC 容器對象,ApplicationContext 代表 IOC 容器//ClassPathXmlApplicationContext 是 ApplicationContext 接口的實現(xiàn)類,該實現(xiàn)類從類路徑下加載xml配置文件。ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//2. 從 IOC 容器中獲取 Bean 實例HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//3. 調(diào)用類的方法 helloWorld.hello();}}?
輸出結(jié)束:
這就是簡單的 Spring HelloWorld。
?
擴展:
為了了解執(zhí)行過程,先把獲取 Bean 對象和調(diào)用對象方法注釋掉,只保留 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml")。
其輸出結(jié)果為:
所以,當執(zhí)行這句代碼的時候,Spring 的容器已經(jīng)幫我們利用反射創(chuàng)建好對象,并根據(jù)配置文件把相應(yīng)的值賦給對象的屬性。接下來我們只要獲取該對象就可以使用它提供的方法了。
?
轉(zhuǎn)載于:https://www.cnblogs.com/sky230/p/5957817.html
總結(jié)
以上是生活随笔為你收集整理的Spring的HelloWorld的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python基础之运算符
- 下一篇: JSON.stringify() / J