zoukankan      html  css  js  c++  java
  • Spring、Bean的生命周期

    1、默认情况下,在Bean容器被实例化的时候,bean对象将被创建:

    public class PersonServiceImpl implements PersonIService {
    
    	public PersonServiceImpl(){
    		System.out.println("初始化!!!");
    	}
    	@Override
    	public void helloSpring() {
    		System.out.println("Hello Spring!");
    	}
    }

    <bean id="personIService" class="cn.server.impl.PersonServiceImpl"/>

    测试:

    	@Test
    	public void test() {
    		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		//PersonIService personIService=(PersonIService)ac.getBean("personIService");
    	}

    结果:



    2、设置bean的lazy-init属性可以决定Bean是的实例对象是否使用懒加载,默认lazy-init=“false”:   当lazy-init设置为True的时候,只有Bean被实例的时候才调用:

    	@Test
    	public void test() {
    		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		PersonIService personIService=(PersonIService)ac.getBean("personIService");
    	}

    <bean id="personIService" class="cn.server.impl.PersonServiceImpl" lazy-init="true"/>

    3、在bean被实例之前和在bean实例之后都可以执行某些方法,只要设置bean的init-method属性和destroy-method方法即可:

    public class PersonServiceImpl implements PersonIService {
    
    	public void initBean(){
    		System.out.println("被实例之前调用");
    	}
    	public void destoryBean(){
    		System.out.println("实例被关闭之后调用");
    	}
    	@Override
    	public void helloSpring() {
    		System.out.println("Hello Spring!");
    	}
    }

    <bean id="personIService" class="cn.server.impl.PersonServiceImpl" 
    	lazy-init="false" init-method="initBean" destroy-method="destoryBean"/>

    测试代码:

    	@Test
    	public void test() {
    		AbstractApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		PersonIService personIService=(PersonIService)ac.getBean("personIService");
    		personIService.helloSpring();
    		ac.close();
    	}



  • 相关阅读:
    CodeforcesBeta Round #19 D. Points 离线线段树 单点更新 离散化
    挑战练习题3.3 POJ 2886 Who Gets the Most Candies? 树状数组
    hdu4288 Coder 离线线段树 单点更新 区间求和 离散化?
    zoj 1610 Count the Colors 线段树 区间更新
    51nod 1307 绳子与重物 二分+dfs / 并查集
    51nod 1116 K进制下的大数 暴力/数论
    Wannafly2016-12-27 SPOJ-INTSUB 数学
    C++——Vector
    LEDE Project
    Raspberry Pi 3 with Openwrt
  • 原文地址:https://www.cnblogs.com/raphael5200/p/5114742.html
Copyright © 2011-2022 走看看