Spring Bean

来源:互联网 发布:儿童英语网络课程代理 编辑:程序博客网 时间:2024/06/08 02:45
一、 Bean的配置项及作用
Id
唯一标识
Class
要实例化的类
Scope
作用域
Constructor arguments
构造器的参数
Properties
属性
Autowiring mode
自动装配模式
lazy-initialization mode
懒加载
Initialization/destruction method
初始化、销毁方法

二、Bean的作用域
1、singleton:单例(默认),指一个Bean容器中只存在一份
2、prototype:每次请求(每次使用)创建新的实例,destroy方式不生效
3、request:每次http请求创建一个实例且仅在当前request内有效
4、session:每次http请求创建,当前session内有效
5、global session:基于portlet的web中有效(portlet定义了global session),如果是在web中,同session

三、Bean的生命周期
1、 定义
2、初始化
    方法一:实现 org.spingframework.beans.factory.InitializingBean接口,覆盖afterPropertiesSet方法
         public class className implents InitializingBean{
            @Override
            public void afterPropertiesSet() throws Exception{
            }
         }
    方法二:配置init-method
        <bean id="id" class="className" init-method="init"/>
        public class className{
            public void init(){}
        }
3、 使用
4、 销毁
    方法一:实现 org.spingframework.beans.factory.DisposableBean接口,覆盖destroy方法
         public class className implents DisposableBean{
            @Override
            public void destroy() throws Exception{
            }
         }
    方法二:配置destroy-method
        <bean id="id" class="className" destroy-method="cleanup"/>
        public class className{
            public void cleanup(){}
        }

配置全局默认初始化、销毁方法    
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="init" default-destroy-method="destroy">
</beans>

若同时使用三种初始化、销毁方式,则默认的会被屏蔽掉,先执行接口的,后执行配置的。
默认方式为可选,即使类中没有声明使用到的方法也不会报错,但是接口、配置用到的方法必须被声明
0 0