Spring中Bean的使用

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 ? 在CODE上查看代码片 派生到我的代码片
  1. public class TopicService   
  2. {  
  3.     public void addTopic()  
  4.     {  
  5.         System.out.println("add topic");  
  6.     }  
  7. }  

xml配置bean

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.        xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.                            http://www.springframework.org/schema/beans/spring-beans.xsd">  
  6.   
  7.     <!-- 生产任意内容 -->  
  8.     <bean id="topServiceID" class="com.canyugan.scope.TopicService"></bean>  
  9.       
  10. </beans>  

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

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. @Test  
  2.     public  void demo1()  
  3.     {   
  4.         String xmlpath="com/canyugan/scope/beans.xml";  
  5.         ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlpath);  
  6.           
  7.         TopicService topicService1=applicationContext.getBean("topServiceID",TopicService.class);  
  8.         System.out.println(topicService1);  
  9.         TopicService topicService2=applicationContext.getBean("topServiceID",TopicService.class);  
  10.         System.out.println(topicService2);  
  11.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值