首页 > 编程语言 > 详细

spring in action 学习笔记九:如何证明在scope为prototype时每次创建的对象不同。

时间:2017-06-09 13:04:57      阅读:359      评论:0      收藏:0      [点我收藏+]

  spring 中scope的值有四个:分别是:singleton、prototype、session、request。其中session和request是在web应用中的。

下面证明当scope为prototype时每次创建的对象是不同的。

示例代码如下:

 1 package com.advancedWiring.ambiguityIniAutowiring2;
 2 
 3 import org.springframework.beans.factory.BeanNameAware;
 4 import org.springframework.beans.factory.config.ConfigurableBeanFactory;
 5 import org.springframework.context.annotation.Scope;
 6 import org.springframework.stereotype.Component;
 7 
 8 /**
 9  * Created by ${秦林森} on 2017/6/9.
10  */
11 @Component
12 @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
13 public class Student implements BeanNameAware{
14     private  String name;
15     private Integer age;
16 
17     public String getName() {
18         return name;
19     }
20 
21     public void setName(String name) {
22         this.name = name;
23     }
24 
25     public Integer getAge() {
26         return age;
27     }
28 
29     public void setAge(Integer age) {
30         this.age = age;
31     }
32 
33     @Override
34     public void setBeanName(String name) {
35         System.out.println("the Student bean name is :"+name);
36     }
37 }
 1 package com.advancedWiring.ambiguityIniAutowiring2;
 2 
 3 import org.springframework.beans.factory.config.ConfigurableBeanFactory;
 4 import org.springframework.context.annotation.Bean;
 5 import org.springframework.context.annotation.ComponentScan;
 6 import org.springframework.context.annotation.Configuration;
 7 import org.springframework.context.annotation.Scope;
 8 
 9 /**
10  * Created by ${秦林森} on 2017/6/9.
11  */
12 @Configuration
13 @ComponentScan
14 public class StudentConfig {
15 
16 }
 1 package com.advancedWiring.ambiguityIniAutowiring2;
 2 
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 import org.springframework.context.support.ClassPathXmlApplicationContext;
 5 
 6 /**
 7  * Created by ${秦林森} on 2017/6/9.
 8  */
 9 public class Test {
10     public static void main(String[] args) {
11     
12         AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(StudentConfig.class);
13         Student student = ac.getBean(Student.class);
14         Student student2 = ac.getBean(Student.class);
15         System.out.println(student==student2);
16     }
17 }/**output:
false/

上面的测试类的运行结果是false,就说明了在scope为prototype时,spring每次创建的bean都是一个全新的对象。

spring in action 学习笔记九:如何证明在scope为prototype时每次创建的对象不同。

原文:http://www.cnblogs.com/1540340840qls/p/6971485.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!