spring bean作用域

来源:互联网 发布:淘宝客去哪里推广 编辑:程序博客网 时间:2024/05/17 09:03
***singleton(单例,默认值)***单例模式的意思就是只有一个实例,分为饿汉式(加载类时就初始化实例)懒汉式(第一次调用getInstance()时才生成实例)两种实现方案。一、创建类:public class UserDaoImpl implements UserDao {    public UserDaoImpl() {        System.out.println("初始化了UserDaoImpl.");    }}二、配置文件:<bean id="userDao" class="cn.itcast.f_beanScope.UserDaoImpl"/>或是:<bean id="userDao" scope="singleton" class="cn.itcast.f_beanScope.UserDaoImpl"/>或是:<bean id="userDao" lazy-init="true" class="cn.itcast.f_beanScope.UserDaoImpl"/>三、测试代码:@Testpublic void test1() {    ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml", getClass());    System.out.println("-- 还未执行获取bean的方法 --");    Object dao1 = ac.getBean("userDao");    Object dao2 = ac.getBean("userDao");    System.out.println(dao1 != null); // true(不为null)    System.out.println(dao1 == dao2); // true(相等,即同一个实例)}四、对所有bean都应用延迟初始化:方法是在根节点beans中设置属性default-lazy-init=“true“,如下所示:<beans default-lazy-init="true" ...>
***prototype(原型,表示每次获取的都是新对象)***<bean id="userDao" scope="prototype" class="cn.itcast.f_beanScope.UserDaoImpl"/>
***指定Bean的初始化方法和销毁方法***一、创建类:public class UserDaoImpl implements UserDao {    public void init() {        System.out.println("UserDaoImpl初始化了");    }    public void destroy() {        System.out.println("UserDaoImpl销毁了");    }}二、配置:<bean id="userDao" scope="singleton" init-method="init" destroy-method="destroy"    class="cn.itcast.g_init_destroy.UserDaoImpl"/>三、测试代码:@Testpublic void test1() {    ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml", getClass());    Object dao = ac.getBean("userDao");    System.out.println(dao);    ac.close(); // 一定要关闭才会执行destroy-method( bean的scope也不能是prototype)}四、注意:1,如果scope属性为prototype则不受spring缓存的控制,destory方法也将不会执行(scope调为singleton时才会有效)。2,要调用ApplicationContext的close()方法才会执行destory方法(在ApplicationContext接口中没有close()方法,需要强转为具体的实现类才可以调用)
0 0