Spring之Hello World

Spring之Hello World

1.下载Spring相关的开发包
下载地址:http://sourceforge.net/project/showfiles.php?group_id=73357
有spring-framework-1.2.6-with-dependencies.zip,一個是spring-framework-1.2.6.zip,最好下载with-dependencies的,里面有另外一些附加包,下载后解压缩,dist目录下是spring自身的jar,lib目录下是附加的jar。
2.新建Java Project,将spring.jar(dist目录下)和commons-logging.jar(lib目录下)添加到project的build path中。
3.新建POJO Bean类:HelloBean
//HelloBean.java
/**
 *
 */
package com.lzy;

/**
 * @author lzy
 *
 */
public class HelloBean{
 
 private String hello;
 
 public void sayHello(){
  System.out.println(this.getHello());
 }

 /**
  * @return Returns the hello.
  */
 public String getHello() {
  return hello;
 }

 /**
  * @param hello The hello to set.
  */
 public void setHello(String hello) {
  this.hello = hello;
 }
 

}


4.新建文件bean.xml,将在这个XML文件中为一个HelloBean的实例的hello属性赋值。
//bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<description>Spring Quick Start</description>
<bean id="helloBean" class="com.lzy.HelloBean">
  <property name="hello">
   <value>hello world</value>
  </property>
</bean>
</beans>

5.新建测试类:TestSpring
//TestSpring.java
/**
 *
 */
package com.lzy;

import java.util.Locale;

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

/**
 * @author lzy
 *
 */
public class TestSpring {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  ApplicationContext ctx=new FileSystemXmlApplicationContext("bean.xml");
    HelloBean hello=(HelloBean)ctx.getBean("helloBean");
  hello.sayHello();
 }

}


6.运行测试类:
    如果没有出错,输出中将会看到“hello world”。

你可能感兴趣的:(Spring之Hello World)