一、了解Spring
Spring是一个开源的框架,为了简化企业级应用开发而生。使用Spring可以简化JavaBean实现以前只有EJB才能实现的功能。Spring是一个IOC(DI)和AOP容器框架。
二、Spring的具体描述
轻量级:Spring是非侵入性的,基于Spring开发的应用中的对象可以不依赖于Spring的API;
依赖注入:(DI:dependency injection、IOC);
面向切面编程:(AOP:aspect oriented programming);
容器:Spring是一个容器,因为他包含并且管理应用对象的生命周期;
框架:Spring实现了使用简单的组件配置组合成一个复杂的应用,在Spring中可以使用XML和java注解组合这些对象;
一站式:在IOC和AOP的基础上可以整合各种企业应用的开源框架和优秀的第三方类库(实际上Spring自身也提供了展现层的SpringMVC和持久层的Spring JDBC);
三、Spring模块图解
四、我的第一个helloword
上次我配置了springsource tool suite,今天就在spring上写一个简单的helloword。
在eclipse中新建一个java project(file→New→java project),起名Spring-1。在工程下面新建一个lib,将commons-logging-1.2.jar、spring-beans-3.2.9.RELEASE.jar、spring-context-3.2.9.RELEASE.jar、spring-core-3.2.9.RELEASE.jar、spring-expression-3.2.9.RELEASE.jar。粘贴复制到lib下面,然后选中这几个jar包,build path→confiure build path。这样基础的环境就配置完了。
在src中新建包(com.atguigu.spring.beans),在新建的包中新建类HelloWord.class。
public class HelloWord {
private String name;
public void setName(String name) {
this.name=name;
}
public void hello() {
System.out.println("hello: "+name);
}
}
在src中新建spring bean configuration file,在该文件中新建bean。
<!-- 配置bean -->
<bean id="helloword" class="com.atguigu.spring.beans.HelloWord">
<property name="name" value="spring"></property>
</bean>
在com.atguigu.spring.beans中新建Main.class。
//1、创建Spring的IOC容器对象
ApplicationContext cxt= new ClassPathXmlApplicationContext("applicationContext.xml");
//2.从IOC容器中获取Bean实例
HelloWord hw=(HelloWord) cxt.getBean("helloword");
//3.调用hello方法
hw.hello();
可以看到用ApplicationContext对象创建Spring的IOC容器对象,然后通过getBean在TOC容器中获取helloword实例,获取实例之后,强制转换成对象,然后调用hello方法执行。
这样一个完整的helloword就创建完成了。
五、验证Spring的IOC容器做了什么事情
下面我们来研究下ApplicationContext cxt= new ClassPathXmlApplicationContext("applicationContext.xml");都做了些什么?
我们来改造一下HelloWord.class,我们创建了一个无参的构造器。
public class HelloWord {
private String name;
public void setName(String name) {
System.out.println("SetName: "+name);
this.name=name;
}
public void hello() {
System.out.println("hello: "+name);
}
//创建一个无参的构造器
public HelloWord() {
System.out.println("正在初始化一个构造器");
}
}
然后在Main中只执行第一步(创建spring的IOC容器),查看一下执行的结果:
正在初始化一个构造器
SetName: spring
可以看到在创建spring的IOC容器中,首先是初始化了一个构造器,然后调用了setName函数给name赋值。
写在后面:这个是根据尚硅谷的spring视频学习整理的笔记,尚硅谷的视频对于初学者是一些很好的学习材料。