• 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();
    	}
    
    }
    

      

  • 相关阅读:
    菜鸟学JS(一)——上传图片之上传前预览图片
    菜鸟学JS(二)——上传图片之上传后查看大图
    FTP文件操作之下载文件
    FTP文件操作之删除文件
    上传图片之上传前判断文件格式与大小
    FTP文件操作之上传文件
    ASP.NET中的几种弹出框提示
    dbo.fn_trace_gettable
    Blocked Process Report
    extended property
  • 原文地址:https://www.cnblogs.com/E-star/p/3557155.html
Copyright © 2020-2023  润新知