Spring(四)JavaBean作用范围的配置及生命周期

Bean的作用范围有几种:

  • singleton  在每个Spring Ioc容器中一个Bean定义只有一个对象实例。默认情况下会在容器启动时初始化Bean,但我们可以指定Bean节点的lazy-init="true"来延迟初始化Bean,这样只有第一次获取Bean才会初始化Bean。如:

    如果想对所有Bean都应用延迟初始化,可以在根节点beans设置default-lazy-init="true",如下:

  • prototype  每次从容器获取bean都是新的对象
还有三种是应用在web project中的: requestsessionglobal session
package test.spring.jnit;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import test.spring.service.impl.PersonServiceBean;

public class BeanScopeTest {

	@Test
	public void testScope() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"beans.xml");
		// -------------------------------------------------
		PersonServiceBean personServiceBean1 = (PersonServiceBean) applicationContext
				.getBean("personService");
		PersonServiceBean personServiceBean2 = (PersonServiceBean) applicationContext
				.getBean("personService");

		System.out.println(personServiceBean1 == personServiceBean2);

	}
}
按之前的配置这块代码返回true,但如果改变PersonServiceBean的作用范围
	
就会返回false

	
bean的初始化在实例化之后,而销毁即释放资源在Spring容器关闭后
package test.spring.service.impl;

import test.spring.service.PersonService;

public class PersonServiceBean implements PersonService {

	public void init(){
		System.out.println("初始化");
	}
	public PersonServiceBean(){
		System.out.println("现在实例化");
	}
	@Override
	public void save(){
		System.out.println("=============");
	}
	public void destroy() {
		System.out.println("释放资源");
	}
}

package test.spring.jnit;

import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanScopeTest {

	@Test
	public void testScope() {
		// ApplicationContext applicationContext = new
		// ClassPathXmlApplicationContext(
		// "beans.xml");// 如果scope="singleton",现在对bean实例化
		// System.out.println("-------------------------------");
		/*
		 * 如果scope="prototype",现在对bean实例化。
		 * 如果scope="singleton",通过设置lazy-init="true"延迟实 例化的时间,bean也在此时实例化。
		 */
		// PersonServiceBean personServiceBean1 = (PersonServiceBean)
		// applicationContext
		// .getBean("personService");
		// PersonServiceBean personServiceBean2 = (PersonServiceBean)
		// applicationContext
		// .getBean("personService");
		//
		// System.out.println(personServiceBean1 == personServiceBean2);//
		// 返回true
		AbstractApplicationContext abstractApplicationContext = new ClassPathXmlApplicationContext(
				"beans.xml");
		abstractApplicationContext.close();
	}
}
Spring(四)JavaBean作用范围的配置及生命周期_第1张图片

你可能感兴趣的:(web)