Spring從開始到精通HelloSpring

1新建一個java項目名字叫hellospring點finish

操作: file->new -> Java Project輸入工程名稱後點finsh


2新建com.vsked.test包

操作:右擊src文件夾new->Package輸入com.vsked.test



3新建存放spirng4.0 jar包目錄

操作:右擊工程->new->Folder取名lib

將Spring4.0需要的jar包放進去

用到的包有

commons-logging-1.1.3.jar
spring-aop-4.0.0.M3.jar
spring-aspects-4.0.0.M3.jar
spring-beans-4.0.0.M3.jar
spring-context-4.0.0.M3.jar
spring-context-support-4.0.0.M3.jar
spring-core-4.0.0.M3.jar
spring-expression-4.0.0.M3.jar


4在com.vsked.test中新建類HelloWorld

package com.vsked.test;

public class HelloWorld {
	   private String message;

	   public void setMessage(String message){
	      this.message  = message;
	   }

	   public void getMessage(){
	      System.out.println("Your Message : " + message);
	   }
}



5在com.vsked.test包中新建MainApp類

package com.vsked.test;

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

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context =  new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorldBean");

      obj.getMessage();
   }
}

6在src目錄下新建Beans.xml


<?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-3.0.xsd">

   <bean id="helloWorldBean" class="com.vsked.test.HelloWorld">
       <property name="message" value="Hello Spring is here!"/>
   </bean>

</beans>

7當前工程目錄佈局

8運行下MainApp看下效果




代碼運行流程:

1通過ClassPathXmlApplicationContect找到Beans.xml文件

ApplicationContext context =  new ClassPathXmlApplicationContext("Beans.xml");


2聲明一個HelloWorld的實例 這個實例是通過XML配置獲取得到的

HelloWorld obj = (HelloWorld) context.getBean("helloWorldBean");

3在xml中class指明瞭需要注入的類並在類中配置屬性message內容爲Hello Spring is here

   <bean id="helloWorldBean" class="com.vsked.test.HelloWorld">
       <property name="message" value="Hello Spring is here!"/>
   </bean>

4實例化完成後調用通過xml注入的類中getMessage()方法

obj.getMessage();


5取到了xml中配置的message值


原文地址:http://www.tutorialspoint.com/spring/spring_hello_world_example.htm

示例代碼下載地址:http://download.csdn.net/detail/chousheng/6672867

本示例包括用到的所有jar包!要1分不要說貴少年們



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章