Spring教程-Spring示例

Spring示例
在这里,我们将学习创建第一个Spring应用程序的简单步骤。为了运行这个应用程序,我们不使用任何集成开发环境(IDE),而是简单地使用命令提示符。让我们看一下创建Spring应用程序的简单步骤:
- 创建类
- 创建XML文件以提供值
- 创建测试类
- 加载Spring Jar文件
- 运行测试类
创建Spring应用程序的步骤
让我们来看看创建第一个Spring应用程序的5个步骤。
1) 创建Java类
这是一个简单的Java bean类,只包含name
属性。
package cn.javatiku;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void displayInfo() {
System.out.println("Hello: " + name);
}
}
这是一个简单的bean类,只包含一个名为name
的属性及其getter和setter方法。该类还包含一个名为displayInfo()
的额外方法,它通过hello消息打印学生的名字。
2) 创建XML文件
如果使用MyEclipse集成开发环境,您无需手动创建XML文件,因为MyEclipse会自动创建。打开applicationContext.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="studentbean" class="cn.javatiku.Student">
<property name="name" value="javatiku"/>
</bean>
</beans>
bean
元素用于为给定的类定义bean。bean
的property
子元素指定了Student
类的名为name
的属性。在property
元素中指定的值将由IOC容器设置到Student
类对象中。
3) 创建测试类
创建Java类,例如Test
。在这里,我们使用BeanFactory
的getBean()
方法从IOC容器中获取Student
类的对象。让我们看一下测试类的代码:
package cn.javatiku;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Student student = (Student) factory.getBean("studentbean");
student.displayInfo();
}
}
Resource
对象代表applicationContext.xml
文件的信息。Resource
是一个接口,而ClassPathResource
是Resource
接口的实现类。BeanFactory
负责返回bean。XmlBeanFactory
是BeanFactory
的实现类。BeanFactory
接口中有很多方法,其中一个方法是getBean()
,它返回与关联类对应的对象。
4) 加载Spring框架所需的Jar文件
运行此应用程序需要三个主要的Jar文件。
org.springframework.core-3.0.1.RELEASE-A
com.springsource.org.apache.commons.logging-1.1.1
org.springframework.beans-3.0.1.RELEASE-A
对于将来使用,您可以下载用于Spring核心应用程序所需的Jar文件。
5) 运行测试类
现在运行Test
类。您将得到输出:Hello: javatiku。