1. 程式人生 > >Spring入門第一篇(Hello World)

Spring入門第一篇(Hello World)

前面我寫了一篇關於如何在eclipse安裝Spring的文章

現在開始第一個spring專案Hello world

準備工作

把上面的檔案解壓到同一個目錄下

新建一個Java 專案,右鍵New–>Project

在這裡插入圖片描述

在這裡插入圖片描述

在專案目錄下一個資料夾lib

將spring-framework-4.2.4.RELEASE\libs下的這幾個檔案和commons-logging-1.2下的commons-logging-1.2.jar拷到我們新建的lib裡面 在這裡插入圖片描述 加入build path,右鍵點選專案——properties——java build path,在libraries標籤下點——add JARs… 在這裡插入圖片描述

新增firstSpring\lib裡面的jar包 然後點Apply and close

建立檔案

在src下建立一個包 在這裡插入圖片描述

新建HelloWorld.java

package demo;

public class HelloWorld {
	 
	public void say(){
		System.out.println("|^^^^^^^^^^^^^^^^^^^^^^^|");
		System.out.println("|      hello world      |");
		System.out.println("|_______________________|");
		System.out.println("Spring 入門第一篇!");
	}
}

新建Main.java

package demo;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
	 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ApplicationContext a = new ClassPathXmlApplicationContext("classpath:/application.xml");
        HelloWorld hello = a.getBean("HelloWorld",HelloWorld.class);
	    hello.say();
	}
 
}
  • 注意:需要手動匯入兩個包
  • import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;

不然會報錯: 在這裡插入圖片描述

然後在src下建立application.xml 在這裡插入圖片描述

在這裡插入圖片描述

選擇Spring Bean Configuration File

<?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 id="HelloWorld" class="demo.HelloWorld"></bean>**
</beans>

新增bean這一行

然後在Main下點選application 在這裡插入圖片描述

結果如下:

在這裡插入圖片描述