spring 创建应用

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

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


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

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

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核心jar文件。

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

3、创建Java类

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

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

4、创建xml文件

创建xml文件单击src-新建-file-给出文件名,例如applicationContext.xml-完成。打开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.nhooo.Student">
<property name="name" value="Vimal Jaiswal"></property>
</bean>
</beans>

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

5、创建测试类

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

package com.nhooo;
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。

spring with eclipse IDE