Bean的装配(1)

  • bean的作用域

singleton:单例,指一个Bean容器中只存在一份。(默认)
prototype:每次请求(每次使用)创建心得实例,destroy方式不生效
request:每次http请求创建一个实例且仅在当前request内生效
session:同上,每次http请求创建,当前session内有效 global
session:基于portlet的web中有效,如果是在web中,同session

  • bean的生命周期
    bean的生命周期有:定义,初始化,使用,销毁。

初始化方法有三种实现方式:

1:在配置文件中:

<bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"  init-method="start" ></bean>`

在实现类中:

    public void start() {
        System.out.println("Bean start .");
    }

2:在配置文件中不配置,实现org.springframework.beans.factory.InitializingBean借口,覆盖afterPropertiesSet方法。

在实现类中:

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Bean afterPropertiesSet.");
    }

3:设置全局方法

<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" 
        default-init-method="defautInit" >

在实现类中:

public void defautInit() {
System.out.println(“Bean defautInit.”);
}


销毁方法同有三种实现方式:

1:在配置文件中:

<bean id="beanLifeCycle" class="com.imooc.lifecycle.BeanLifeCycle"   destroy-method="stop"></bean>`

在实现类中:

    public void stop() {
        System.out.println("Bean stop.");
    }

2:在配置文件中不配置,实现org.springframework.beans.factory.DisposableBean借口,覆盖destroy方法。

在实现类中:

    @Override
    public void destroy() throws Exception {
        System.out.println("Bean destroy.");
    }

3:设置全局方法

<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" 
       default-destroy-method="defaultDestroy">

实现类:

    public void defaultDestroy() {
        System.out.println("Bean defaultDestroy.");
    }

当spring的初始化和销毁的第1个和第二个方法已经定义和实现,那么,全局默认的方法既第三个方法则不会实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值