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分不要说贵少年们



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