【译文】【学习】Spring Bean 范围
【目标读者】
本教程是专为java编程人员设计的,用来帮助他们理解Spring 3框架以及基于它的应用。
【前置条件】
在阅读教程之前你应该有一个比较好对java语言知识的理解
【系列教程】
Introduction to spring framework
Dependency injection(ioc) in spring
Spring hello world example in eclipse
Spring java based configuaration
Dependency injection via setter method in spring
Dependency injection via constructor in spring
Spring Bean scopes with examples
Initializing collections in spring
Annotation based Configuration in spring
【Spring Bean范围】
在Spring中, Bean的Scope用来决定bean的那种类型实例应该被Spring容器返回给调用者。有五中类型的bean scope可供选择:
singleton - 每个Spring容器仅有一个实例,单例
prototype - 每次请求都返回一个新的实例
request - 每一个HTTP请求返回一个实例
session - 每一个HTTP会话返回一个实例
globalsession - 每一个全局HTTP会话返回一个实例
用的最多的当是singleton和prototype。默认是singleton。
【Singleton Scope】
<bean id="country" class="org.arpit.javapostsforlearning.Country">
使用上述配置,默认是singleton。然后使用如下代码调用,结果是每次获取id为country的实例都是同一个,输出同样的信息。
public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj1 = (Country) appContext.getBean("country"); countryObj1.setCountryName("India"); System.out.println("Country Name:"+countryObj1.getCountryName()); //getBean called second time Country countryObj2 = (Country) appContext.getBean("country"); System.out.println("Country Name:"+countryObj2.getCountryName()); }
第一次获取id为country的bean,然后设置属性,并输出;第二次获取同样的bean时,输出结果为先前设置的属性,因此是属于同一个实例。
【prototype scope】
<bean id="country" class="org.arpit.javapostsforlearning.Country" scope="prototype">
使用如上配置,用如下方法调用,俩个获取的实例并无关联。
public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext("ApplicationContext.xml"); Country countryObj1 = (Country) appContext.getBean("country"); countryObj1.setCountryName("India"); System.out.println("Country Name:"+countryObj1.getCountryName()); //getBean called second time Country countryObj2 = (Country) appContext.getBean("country"); System.out.println("Country Name:"+countryObj2.getCountryName()); }
第二次输出为null,说明俩次获取的并不是同一个实例。

浙公网安备 33010602011771号