个性化阅读
专注于IT技术分析

Eclipse IDE创建Spring应用程序详细步骤实例

  1. 在Eclipse中创建Spring应用程序
  2. 在Eclipse中创建Spring应用程序的步骤

在这里, 我们将使用eclipse IDE创建一个spring框架的简单应用程序。让我们看一下在Eclipse IDE中创建spring应用程序的简单步骤。

  • 创建Java项目
  • 添加spring jar文件
  • 创建课程
  • 创建xml文件以提供值
  • 创建测试类

在Eclipse IDE中创建Spring应用程序的步骤

让我们看一下使用eclipse IDE创建第一个spring应用程序的5个步骤。

1)创建Java项目

转到文件菜单-新建-项目-Java项目。输入项目名称, 例如firstspring-完成。现在, 创建了Java项目。

2)添加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文件。

下载Spring的核心jar文件

下载Spring的所有jar文件, 包括aop, mvc, j2ee, remoting, oxm等。

要运行此示例, 你只需要加载spring core jar文件。

要在Eclipse IDE中加载jar文件, 请右键单击你的项目-构建路径-添加外部档案-选择所有必需的jar文件-完成。

3)创建Java类

在这种情况下, 我们只是在创建Student类的具有name属性。学生的姓名将由xml文件提供。这只是一个简单的示例, 而不是spring的实际使用。我们将在”依赖注入”一章中看到实际的用法。要创建Java类, 请右键单击src-新建-类-输入类名称, 例如学生-完成。编写以下代码:

package com.srcmini;

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类, 仅包含一个带有其getters和setters方法的属性名。此类包含一个名为displayInfo()的附加方法, 该方法通过hello消息打印学生姓名。

4)创建xml文件

要创建xml文件, 请单击src-new-file-给出文件名, 例如applicationContext.xml-finish。打开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="com.srcmini.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>

</beans>

bean元素用于为给定类定义bean。 bean的属性子元素指定了名为name的Student类的属性。属性元素中指定的值将由IOC容器在Student类对象中设置。

5)创建测试类

创建java类, 例如测试。在这里, 我们使用BeanFactory的getBean()方法从IOC容器中获取Student类的对象。让我们看一下测试类的代码。

package com.srcmini;

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();
}
}

现在运行此类。你将得到输出Hello:Vimal Jaiswal。

带有Eclipse IDE的Spring

下载此示例

赞(0)
未经允许不得转载:srcmini » Eclipse IDE创建Spring应用程序详细步骤实例

评论 抢沙发

评论前必须登录!