您的位置:首页 > 编程语言 > Java开发

Spring中Bean的使用

2016-05-22 22:35 555 查看
1:和变量一样,bean也有作用域,spring中我们可以为bean指定作用域:<bean id="" class=""  scope="....">

2:作用域的种类

singleton:单例模式,在spring中只有一个实例,无论多少个Bean引用,始终都会指向同一个对象。这也是spring默认的作用域。

prototype:原型模式,spring容器会为每一个引用创建一个新实例。

request:每一个HTTP请求都会创建一个新的bean,但仅仅在当前的request中有效。

session:每一个HTTP Session都会创建一个新的bean,但仅仅在当前HTTP Session中有效。

global Session:在一个全局的HTTP Session中,容器会创建实例,但仅仅在当前范围有效。



实际开发中,单例和原型用的比较多。





3:演示单例模式作用域



bean定义



[java] view
plain copy

 print?





public class TopicService   

{  

    public void addTopic()  

    {  

        System.out.println("add topic");  

    }  

}  

xml配置bean



[java] view
plain copy

 print?





<?xml version="1.0" encoding="UTF-8"?>  

<beans xmlns="http://www.springframework.org/schema/beans"  

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

       xsi:schemaLocation="http://www.springframework.org/schema/beans   

                           http://www.springframework.org/schema/beans/spring-beans.xsd">  

  

    <!-- 生产任意内容 -->  

    <bean id="topServiceID" class="com.canyugan.scope.TopicService"></bean>  

      

</beans>  

测试单例模式下是否引用的是同一个实例:



[java] view
plain copy

 print?





@Test  

    public  void demo1()  

    {   

        String xmlpath="com/canyugan/scope/beans.xml";  

        ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlpath);  

          

        TopicService topicService1=applicationContext.getBean("topServiceID",TopicService.class);  

        System.out.println(topicService1);  

        TopicService topicService2=applicationContext.getBean("topServiceID",TopicService.class);  

        System.out.println(topicService2);  

    }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: