1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.context.annotation.configuration;
18
19 import org.junit.Test;
20
21 import org.springframework.beans.factory.ObjectFactory;
22 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
23 import org.springframework.context.annotation.Bean;
24 import org.springframework.context.annotation.Configuration;
25 import org.springframework.context.annotation.Scope;
26 import org.springframework.context.annotation.ScopedProxyMode;
27
28 import static org.hamcrest.Matchers.*;
29 import static org.junit.Assert.*;
30
31
32
33
34 public class Spr10744Tests {
35
36 private static int createCount = 0;
37
38 private static int scopeCount = 0;
39
40
41 @Test
42 public void testSpr10744() throws Exception {
43 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
44 context.getBeanFactory().registerScope("myTestScope", new MyTestScope());
45 context.register(MyTestConfiguration.class);
46 context.refresh();
47
48 Foo bean1 = context.getBean("foo", Foo.class);
49 Foo bean2 = context.getBean("foo", Foo.class);
50 assertThat(bean1, sameInstance(bean2));
51
52
53 assertThat(createCount, equalTo(0));
54 assertThat(scopeCount, equalTo(0));
55
56
57 bean1.getMessage();
58 assertThat(createCount, equalTo(1));
59 assertThat(scopeCount, equalTo(1));
60 bean1.getMessage();
61 assertThat(createCount, equalTo(2));
62 assertThat(scopeCount, equalTo(2));
63
64 context.close();
65 }
66
67
68 private static class MyTestScope implements org.springframework.beans.factory.config.Scope {
69
70 @Override
71 public Object get(String name, ObjectFactory<?> objectFactory) {
72 scopeCount++;
73 return objectFactory.getObject();
74 }
75
76 @Override
77 public Object remove(String name) {
78 return null;
79 }
80
81 @Override
82 public void registerDestructionCallback(String name, Runnable callback) {
83 }
84
85 @Override
86 public Object resolveContextualObject(String key) {
87 return null;
88 }
89
90 @Override
91 public String getConversationId() {
92 return null;
93 }
94 }
95
96
97 static class Foo {
98
99 public Foo() {
100 createCount++;
101 }
102
103 public String getMessage() {
104 return "Hello";
105 }
106 }
107
108
109 @Configuration
110 static class MyConfiguration {
111
112 @Bean
113 public Foo foo() {
114 return new Foo();
115 }
116 }
117
118
119 @Configuration
120 static class MyTestConfiguration extends MyConfiguration {
121
122 @Bean
123 @Scope(value = "myTestScope", proxyMode = ScopedProxyMode.TARGET_CLASS)
124 @Override
125 public Foo foo() {
126 return new Foo();
127 }
128 }
129
130 }