Spring作用域和周期方法配置

1 周期方法配置

1.1 周期方法概念

我们可以在组件类中定义方法,然后当IoC容器实例化和销毁组件对象的时候进行调用!这两个方法我们成为生命周期方法!
类似于Servlet的init/destroy方法,我们可以在周期方法完成初始化和释放资源等工作。

1.2 周期方法声明

public class BeanOne {
    public void init(){
        System.out.println("初始化");
    }

    public void clear(){
        System.out.println("销毁");
    }
}

1.3 周期方法配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    init-method 初始化方法-->
<!--    destroy-method 销毁方法-->
    <bean id="beanOne" class="com.lx.ioc_04.BeanOne" init-method="init" destroy-method="clear"></bean>
</beans>

2 组件作用域配置

2.1 Bean作用域概念

<bean 标签声明Bean,只是将Bean的信息配置给SpringIoC容器!
在IoC容器中,这些<bean标签对应的信息转成Spring内部 BeanDefinition 对象,BeanDefinition 对象内,包含定义的信息(id,class,属性等等)!
这意味着,BeanDefinition概念一样,SpringIoC容器可以可以根据BeanDefinition对象反射创建多个Bean对象实例。
具体创建多少个Bean的实例对象,由Bean的作用域Scope属性指定!

2.2作用域scope可选值

取值含义创建对象的时机默认值
singleton在 IOC 容器中,这个 bean 的对象始终为单实例IOC 容器初始化时
prototype这个 bean 在 IOC 容器中有多个实例获取 bean 时
如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):
取值含义创建对象的时机默认值
------------------------
request请求范围内有效的实例每次请求
session会话范围内有效的实例每次会话

2.3 作用域配置

public class BeanTwo {
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- scope属性:取值singleton(默认值),bean在IOC容器中只有一个实例,IOC容器初始化时创建对象 -->
    <!-- scope属性:取值prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象 -->
    <bean id="beanTwo" class="com.lx.ioc_04.BeanTwo" scope="singleton"/>
</beans>
    @Test
    public void test1(){
        ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring-04.xml");
        BeanTwo bean = classPathXmlApplicationContext.getBean(BeanTwo.class);
        BeanTwo bean1 = classPathXmlApplicationContext.getBean(BeanTwo.class);
        System.out.println(bean == bean1);//true
    }
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值