1.spring容器是什么?
Spring的一个核心模块,用来管理对象
2.如何使用
1)导包---maven中(spring-webmvc 4.8)
2)添加配置文件
<?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:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
</beans>
3)启动spring容器
ApplicationContext ac =
new ClassPathXmlApplicationContext(
"applicationContext.xml");
3.spring容器创建对象的三种方式方式一:
容器调用不带参的构造器。
<bean id="标识符" class="Bean类"/>
方式二: (了解)容器调用类的静态方法(静态工厂)。
使用factory-method属性指定静态方法。
<bean id="标识符" class="Bean类" factory-method="..."/>
方式三: (了解)
实例工厂。<bean id="标识符" factory-bean="id"
factory-method="..."/>
4作用域容器会依据scope属性来决定创建多少个实例。默认情况下,容器对于一个bean的配置,只会创建一个实例。
scope属性值可以为以下两个
prototype:(原型),每getBean一次,就会创建一个新的实例。singleton:(单例,缺省值),只创建一个实例。注:spring容器启动时,会对单例的bean直接创建实例
可以通过lazy-init配置为true来进行延迟加载
5.生命周期
spring容器可以对bean进行生命周期的管理。
init-method:指定初始化方法,容器在创建实例之后,会调用该实例的初始化方法。
detroy-method:指定销毁方法,容器在关闭之前,会调用该实例的销毁方法。
注意,只有当scope="singleton"时,销毁方法才起作用。