Spring-4.Spring容器中的Bean

来源:互联网 发布:淘宝店铺如何冲上销量 编辑:程序博客网 时间:2024/06/06 21:40

        开发者使用spring框架主要是做两件事:①开发bean;②配置bean。对于spring框架来说,他要做的事情就是根据配置文件来创建bean实例,并调用bean实例的方法完成“依赖注入”----所谓Ioc的本质。这就要求开发者在使用spring时,眼中看到的是“XML配置”,心中想的是java代码。具体见Spring--1中讲的。

一、容器中Bean的作用域

Spring支持5中作用域,常用的有两种:

①singleton:单例

②prototype:每次getBean(),都会产生一个新的bean实例。

通过配置scope属性指定bean的作用域。

bean

package codeEETest;public class Person{private int age;}
xml
<bean id="p1" class="codeEETest.Person"></bean><bean id="p2" class="codeEETest.Person" scope="prototype"></bean><bean id="date" class="java.util.Date"></bean>
test

public class BeanTest{public static void main(String[] args)throws Exception{// 以类加载路径下的beans.xml文件创建Spring容器ApplicationContext ctx = newClassPathXmlApplicationContext("codeEETest/beans.xml");    // ①// 判断两次请求singleton作用域的Bean实例是否相等System.out.println(ctx.getBean("p1")== ctx.getBean("p1"));// 判断两次请求prototype作用域的Bean实例是否相等System.out.println(ctx.getBean("p2")== ctx.getBean("p2"));System.out.println(ctx.getBean("date"));Thread.sleep(1000);System.out.println(ctx.getBean("date"));}}
结果:

truefalseWed May 31 16:06:57 CST 2017Wed May 31 16:06:57 CST 2017
说明:date bean默认是singleton,在①时已经创建了!表示此时的一个时间