zoukankan      html  css  js  c++  java
  • Spring管理bean的生命周期

    1: bean的创建:   如果我们默认的scope配置为Singleton的话, bean的创建实在Spring容器创建的时候创建; 如果scope的配置为Prototype的话,bena的创建是在getBean的时候创建的。 同样我们还可以在<bean>的配置中配置lazy-init = ”true“是bean的创建在getBean时。

    2: 我们有时候可能在bean完成之后可能想要打开一些资源。 我们可以配置init-method="init" init方法在调用了类的默认构造函数之后执行

    3: 如果我们想在bean销毁时,释放一些资源。 我们可以配置destroy-method="destroy" destroy方法在bean对象销毁时执行

    package cn.gbx.serviceimpl;
    
    import cn.gbx.service.PersonService;
    
    public class PersonServiceImpl implements PersonService {
    	
    	public PersonServiceImpl() {
    		System.out.println("我被实例化啦");
    	}
    	@Override
    	public void save() {
    		System.out.println("save 方法");
    	}
    	public void init() {
    		System.out.println("打开资源。。。");
    	}
    	public void destroy() {
    		System.out.println("关闭资源....");
    	}
    }
    

      

    <?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-2.5.xsd">
     	<bean id="personService" class="cn.gbx.serviceimpl.PersonServiceImpl" init-method="init" destroy-method="destroy" >
     	</bean>
    </beans>
    

      

    package cn.gbx.Junit;
    
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.gbx.service.PersonService;
    import cn.gbx.serviceimpl.PersonServiceImpl;
    
    public class SpringTest {
    	@Test
    	public void spring1() {
    		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
    		PersonService ps = (PersonService)ctx.getBean("personService");
    		ps.save();
    	}
    
    }
    

      

  • 相关阅读:
    HTML5新特性之文件和二进制数据的操作
    HTML5本地存储之IndexedDB
    HTML5新标签之Canvas
    HTML5 Canvas实战之烟花效果
    Asp.NET core/net 5接口返回实体含有long/int64的属性序列后最后几位变为0的解决
    Aero for WTL application
    C++WTL基于MCI的音频播放器源码
    c++ 深拷贝,浅拷贝,赋值操作的调用情况
    发布一个生成按钮图片的工具 c#写的
    贴图:CImage VS Bitmap
  • 原文地址:https://www.cnblogs.com/E-star/p/3557155.html
Copyright © 2011-2022 走看看