首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring学习之从BeanFactory接口开始-Bean的作用域

2012-10-09 
Spring学习之从BeanFactory接口开始--Bean的作用域先看一下BeanFactory接口的三个子接口:?????????还是很

Spring学习之从BeanFactory接口开始--Bean的作用域

先看一下BeanFactory接口的三个子接口:

Spring学习之从BeanFactory接口开始-Bean的作用域

?

?

?

?

?

?

?

?

?

还是很清楚的

?

ListableBeanFactory:提供访问容器中bean基本信息的方法AutowireCapableBeanFactory:定义了将容器中的bean按某种方式进行自动装配的方法HierarchicalBeanFactory:提供了访问父容器的方法,这样就使得spring具有父子级联的IOC容器看一下BeanFactory定义的方法Spring学习之从BeanFactory接口开始-Bean的作用域
在BeanFactory中的方法,很普通,但是需要特别注意的是isPrototype,isSingleton这两个方法,因为这涉及到Bean的作用域的概念。
在isSingleton方法注释中是这样描述的public class HelloBean { private String helloWorld; private int i = (int) (100 * Math.random()); public HelloBean(String helloWorld) { this.helloWorld = helloWorld; } public void sayHello() { System.out.println(helloWorld); System.out.println("输出随机整数: " + i); }}?<beans>
    <bean id="singletonBean" name="code">    public static void main(String[] args) {        Resource res = new ClassPathResource("javamxj/spring/basic/singleton/bean.xml");        BeanFactory factory = new XmlBeanFactory(res);        HelloBean h1 = (HelloBean) factory.getBean("singletonBean");        h1.sayHello();                        HelloBean h2 = (HelloBean) factory.getBean("singletonBean");        h2.sayHello();                System.out.println("h1==h2: " + (h1==h2));        System.out.println("");                        HelloBean h3 = (HelloBean) factory.getBean("prototypeBean");        h3.sayHello();                HelloBean h4 = (HelloBean) factory.getBean("prototypeBean");        h4.sayHello();                System.out.println("h3==h4: " + (h3==h4));    }}

?运行结果为:

?

Hello! 这是singletonBean!
输出随机整数:? 7
Hello! 这是singletonBean!
输出随机整数:? 7
h1==h2: true
?Hello! 这是prototypeBean!?
输出随机整数:? 95
Hello! 这是prototypeBean!?
输出随机整数:? 60
h3==h4: false

核心提示:Spring通过某些机制,保证了在其容器下的bean默认均为singleton,也就是说使用者无需自己维护一个singleton方法。
除了singleton作用域外,spring还有prototype,request,session,globalSession几个作用域,这些我在其他文章中再写!
总结一下:BeanFactory本质是一个工厂,创建Bean的工厂(涉及到工厂模式)部分设计模式在Spring中有着非常重要的应用

热点排行