本文研究的主要是spring學習之創建項目 Hello Spring實例代碼,具體如下。
一、創建eclipse項目,引入jar包
1、eclipse創建java project項目 HelloSpring
2、創建lib目錄,加入spring必須的5個jar包
3、選中5個文件,右鍵 -> Build Path -> add to build path
二、編寫spring的hello spring代碼
1、創建包io.spring.beans,并編寫HelloWorld.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
package io.spring.beans; /** * @author 胖胖のALEX E-mail:[email protected] * @version 1.0 */ public class HelloWorld { private String name; public void setName(String name) { this .name = name; } public void hello() { System.out.println( "hello " + name); } } |
2、src右鍵 -> 創建spring bean configuration文件applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
|
<? 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 = "io.spring.beans.HelloWorld" > < property name = "name" value = "大紅" ></ property > </ bean > </ beans > |
3、編寫Main.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
package io.spring.beans; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * @author 胖胖のALEX E-mail:[email protected] * @version 1.0 */ public class Main { public static void main(String[] args) { //1、創建Spring的IOC容器對象 ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml" ); //2、從IOC容器中獲取Bean實例 HelloWorld helloWorld = (HelloWorld) ctx.getBean( "helloWorld" ); //3、調用hello方法 helloWorld.hello(); } } |
輸出結果
當console內打印出紅色spring日志,表示spring應用成功
總結
以上就是本文關于spring學習之創建項目 Hello Spring實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/alex_bean/article/details/51089964