Spring 示例
在这里,我们将学习创建第一个spring应用程序的简单步骤。要运行此应用程序,我们不使用任何IDE。
我们只是在使用命令提示符。
让我们看看创建spring应用程序的简单步骤
创建Java类
1)创建Java类
这是仅包含name属性的简单Java bean类。
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()的附加方法,该方法通过问候消息打印学生姓名。
创建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.nhooo.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.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();
}
}
资源对象表示applicationContext.xml文件的信息。
Resource是接口,而 ClassPathResource 是Reource接口的实现类。
BeanFactory 负责返回Bean。
XmlBeanFactory 是BeanFactory的实现类。
BeanFactory接口中有很多方法。
一种方法是 getBean(),该方法返回关联类的对象。
----------
加载spring jar文件
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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)