Spring 示例

spring 示例

 

在这里,我们将学习创建第一个spring应用程序的简单步骤。要运行此应用程序,我们不使用任何ide。我们只是在使用命令提示符。让我们看看创建spring应用程序的简单步骤:

  • 创建java类
  • 创建xml文件以提供值
  • 创建测试类
  • 加载spring jar文件
  • 运行测试类

 

创建spring应用程序的步骤

让我们看一下创建第一个spring的5个步骤:

1)创建java类

这是仅包含name属性的简单java bean类。

package com.yapf;
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()的附加方法,该方法通过问候消息打印学生姓名。

 

2)创建xml文件

如果使用myeclipse ide, ,您无需创建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="com.yapf.student">
<property name="name" value="vimal jaiswal"></property>
</bean>
</beans>

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

 

3)创建测试类

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

package com.yapf;
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();
}
}

资源对象表示applicationcontext.xml文件的信息。 resource是接口,而 classpathresource 是reource接口的实现类。 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文件。

下载spring的核心jar文件

全部下载spring的jar文件,包括core,web,aop,mvc,j2ee,remoting,oxm,jdbc,orm等。

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

 

5)运行测试类

现在运行test类。您将得到输出hello: vimal jaiswal。

spring application

下一节:spring 创建应用

spring 教程

相关文章