前面说到spring中Bean有三种配置方式:
https://blog.youkuaiyun.com/Sunny5319/article/details/90740358
下面梳理一下基于XML的配置方式及其细节
bean标签
创建bean的三种方式
第一种方式:试用默认构造函数创建
在spring的配置文件中使用bean标签,配以id和class属性之后,且没有其他属性和标签时,采用的就是默认构造函数创建bean对象,此时如果类中没有默认构造函数,则对象无法创建
第二种方式:使用普通工厂中的方法创建对象(使用某个类中的方法创建对象,并存入spring容器)
第三种方式:使用工厂中的静态方法创建对象(使用某个类中的静态方法创建对象,并存入spring容器)
bean对象的作用范围
bean标签的scope属性:
- 作用:用于指定bean的作用范围
- 取值:常用的就是单例的和多例的
- singleton:单例的(默认值)
- prototype:多例的
- request:作用于web应用的请求范围
- session:作用于web应用的会话范围
- global-session:作用于集群环境的会话范围(全局会话范围),当不是集群环境时,它就是session
单例和多例的比较
global session
bean对象的生命周期
- 单例对象
- 出生:当容器创建是对象出生
- 活着:只要容器还在,对象一直活着
- 死亡:容器销毁,对象消亡
- 总结:和容器相同
- 多例对象
- 出生:当我们使用对象时spring框架为我们创建
- 活着:对象只要是在使用过程中就一直活着
- 死亡:当对象长时间不用,且没有别的对象引用时,由java的垃圾回收器回收
demo
Client
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
// ApplicationContext ac = new FileSystemXmlApplicationContext("bean.xml");
// 2.根据id获取bean对象
IAccountService as = (IAccountService) ac.getBean("accountService");
as.saveAccount();
}
AccountServiceImpl
public class AccountServiceImpl implements IAccountService {
public AccountServiceImpl() {
System.out.println("对象创建了。。。。。");
}
public void saveAccount() {
System.out.println("service中的saveAccount方法执行了。。。。。");
}
public void init() {
System.out.println("对象初始化了。。。。。");
}
public void destroy() {
System.out.println("对象销毁了。。。。。");
}
}
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd ">
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"
scope="singleton" init-method="init" destroy-method="destroy"></bean>
</beans>