一起学spring--我的第一个Spring程序,简单粗暴易懂
发布日期:2021-06-30 17:50:55 浏览次数:3 分类:技术文章

本文共 1721 字,大约阅读时间需要 5 分钟。

欢迎来《一起下spring》系列博文第一篇

一、首先让我们来做一个对比:不使用spring和使用spring的区别

1、首先是不使用spring的情况:

创建一个Student对象,里面只有一个方法,用于打印信息。

package com.huai.first;public class Student {	public void printStudent(){		System.out.println("hello, I am a student");	}}
接下来我想写一个main函数,实例化这个Student,并执行这个方法。

package com.huai.first;public class MainTest {	public static void main(String[] args) {		Student stu = new Student();		stu.printStudent();	}}
这就是不使用spring的情况。那如果使用了spring框架了呢?请接着往下面看:

2、使用spring的情况

同样地,我们创建一个Student类,代码和上面一样。

接下来,我同样要写一个main函数来执行Student对象中的方法。应该怎么写?我先贴出代码:

package com.huai.first;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class FirstSpringTest {	public static void main(String[] args) {		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");		Student stu = context.getBean(Student.class);		stu.printStudent();	}}

分析:

(1)、创建一个spring容器

(2)、从spring容器中获取stu对象。

我们来看一下上面这段代码,发现并没有new Student();的操作,没有实例化Student类的对象?怎么可以这样呢?具体怎么回事?原来、、、、、、

===》spring容器帮我们实例化了student对象

所以我们只需要从spring容器中获取student对象就可以了,也就是对应这条语句:

Student stu = context.getBean(Student.class);

好,我们“获得”了student对象,(这里我用‘获得’,而不是‘创建’),那么,我们就可以调用这个student对象的方法了。

为了使得这段代码能够跑起来,我们还需要进行其他两步准备工作:1、添加jar包;2、填写spring的xml配置文件。

1、添加spring的jar包到WEB-INF下的lib文件夹下面:(本博文最下面有下载的链接,粘贴后别忘了右键--build path -- add to build path)

(1)、commons-logging

(2)、spring-aop

(3)、spring-beans

(4)、spring-context

(5)、spring-context-support

(6)、spring-core

(7)、spring-expression

2、增加配置文件:

在src文件夹下面增加applicationContext.xml文件:(重点在于这一句配置语句<bean class="com.huai.first.Student"/>)

这条配置语句的作用是:告诉spring容器,我需要你帮我实例化这个Student对象;(spring容器回答说:没问题,你到时候直接来取这个‘对象’就可以了)

jar包的下载链接

转载地址:https://liangyihuai.blog.csdn.net/article/details/48894737 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:一起学spring--依赖注入---简单粗暴的例子展示
下一篇:如何将spring源码作为导入eclipse中,变成一个普通的项目(git、github)

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月14日 20时14分02秒