Spring篇--01 Spring简介、Spring容器
一.spring是什么?
是一个开源的用来简化应用开发的框架
1.简化开发
spring对常用的api做了封装和简化(比如,对jdbc做了封装,使用spring jdbc来访问数据,就不再需要考虑获取连接和关闭连接了)
2.管理对象
spring提供了一个容器,帮我们创建对象以及建立对象之间的依赖关系。这样做的好处是,降低对象之间的耦合度,方便代码的维护。
3.集成其他框架
spring可以将其它的一些框架集成进来(比如。集成用于任务调试的框架的Quartz),即“不发明重复的轮组”
二、spring容器(核心)
1.spring容器是什么?
spring框架中的一个核心模块,用于管理对象
2.启动spring容器
step1.导包(spring-webmvc)
建立maven项目来管理项目
在pom.xml中
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.8.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
</dependency>
</dependencies>
step2:配置文件
在resource中applicationContext.xml
step3:启动spring容器
3.如何创建对象?
方式一(重点掌握):使用无参构造器
step1:给类添加无参构造器(或者缺省构造器)
public class Student {
public Student() {
System.out.println("Student()");
}
}
step2:使用<bean>元素
<!-- 使用无参构造器创建对象
id:bean的名称,要求唯一
clas属性:类的全限名称(要求包含包名)-->
<bean id="stu1" class="first.Student">
</bean>
<bean id="date1" class="java.util.Date">
</bean>
step3:调用容器的getBean方法来获取
//启动spring容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//System.out.println(ac);
方式二:使用静态工厂方法
通过调用类的静态方法来创建镀锡
<!-- 使用静态工厂方法创建对象
factory-method属性:指定一个静态方法 -->
<bean id="cal1" class="java.util.Calendar" factory-method="getInstance">
</bean>
方式三:使用实例工厂方法
通过调用对象的实例方法来创建对象
<!-- 使用实例工厂方法来创建对象
factory-bean:指定一个bean的id
factory-method:指定一个方法
spring容器会调用这个bean的对应的方法来创建对象 -->
<bean id="time1" factory-bean="cal1" factory-method="getTime">
</bean>
4.作用域
默认情况下,容器对于某个bean,只会创建一个实例,可以设置scope属性为prototype,这样某个bean会创建多个实例
<!-- scope:配置作用域
缺省值是singleton(即一个bean只创建一个实例)
如果只值为prototype(即一个bean会创建多个实例) -->
<bean id="s1" class="scope.ScopeBean" scope="prototype">
</bean>
5.生命周期
初始化方法:
使用init-method属性来指定初始化方法
销毁方法:
使用destory-method属性来指定销毁方法名
注意:spring容器在关闭之前,会先销毁对象,在销毁对象之前,会先调用对象的销毁方法
<!-- init-method属性:指定初始化方法
destory-method属性:用来指定销毁的方法
lazy-init属性:指定是否延迟加载,如果值为true,表示延迟加载 -->
<bean id="mb1" class="scope.MessageBean" init-method="init" destroy-method="destory" lazy-init="true">
</bean>
6.延迟加载
spring容器启动之后,会将所有作用域为单例的bean创建好
指定lazy-init属性值为true,此时,spring容器对于作用域为单例的bean,就不会创建响应的实例了