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

      

  • 相关阅读:
    Python-HTML基础
    异常处理
    反射hasattr; getattr; setattr; delattr
    Python 属性方法、类方法、静态方法、 特殊属性__doc__ (内建属性)
    Python3 day6面向对象
    re模块计算器作业
    re正则表达式:import re ;re.search()
    hashlib模块学习:hmac
    ConfigParser模块,主要应用于对php.ini等格式的配置文件内容读取和生成。删改较少用
    ymal文档格式 处理
  • 原文地址:https://www.cnblogs.com/E-star/p/3557155.html
Copyright © 2011-2022 走看看