當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring的HelloWorld
生活随笔
收集整理的這篇文章主要介紹了
Spring的HelloWorld
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring模塊:
使用 Eclipse 開發,要先安裝 Spring Tool Suite。
安裝過程中,只勾選 Spring IDE 結尾(4個)的即可,并把聯網進行更新去掉(否則聯網速度會變慢)。
?
開發步驟:
1. 加入jar包(5個)
?
?
2. 創建一個 javaBean 類
package cn.jmu.spring.beans;public class HelloWorld {private String name;public void setName(String name) {System.out.println("setName 方法執行...setName: " + name);this.name = name;}public void hello(){System.out.println("Hello: " + name);}/** 構造函數,用來查看該類的對象是什么時候創建的*/public HelloWorld(){System.out.println("HelloWorld 對象創建...");} }?
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"> <!-- 這里其實是使用了反射來創建一個對象。 --><!-- 為 HelloWorld 類的 name 屬性賦值,即會執行 HelloWorld 的 setName方法 --><property name="name" value="Sky"></property></bean></beans>?
4. 使用 IOC 容器創建對象和調用對象的方法。
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) {/** 傳統方法* HelloWorld helloWorld = new HelloWorld();* helloWorld.setName("Sky");* helloWorld.hello();*///1. 創建 Spring 的 IOC 容器對象,ApplicationContext 代表 IOC 容器//ClassPathXmlApplicationContext 是 ApplicationContext 接口的實現類,該實現類從類路徑下加載xml配置文件。ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//2. 從 IOC 容器中獲取 Bean 實例HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");//3. 調用類的方法 helloWorld.hello();}}?
輸出結束:
這就是簡單的 Spring HelloWorld。
?
擴展:
為了了解執行過程,先把獲取 Bean 對象和調用對象方法注釋掉,只保留 ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml")。
其輸出結果為:
所以,當執行這句代碼的時候,Spring 的容器已經幫我們利用反射創建好對象,并根據配置文件把相應的值賦給對象的屬性。接下來我們只要獲取該對象就可以使用它提供的方法了。
?
轉載于:https://www.cnblogs.com/sky230/p/5957817.html
總結
以上是生活随笔為你收集整理的Spring的HelloWorld的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python基础之运算符
- 下一篇: JSON.stringify() / J