-
Notifications
You must be signed in to change notification settings - Fork 0
/
SingletonWithPrototypeTests.java
61 lines (46 loc) · 1.72 KB
/
SingletonWithPrototypeTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package com.example.core.scope;
import static org.assertj.core.api.Assertions.assertThat;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Scope;
public class SingletonWithPrototypeTests {
@RequiredArgsConstructor
static class SingletonBean {
private final PrototypeBean prototypeBean;
public int logic() {
prototypeBean.addCount();
return prototypeBean.getCount();
}
}
@Scope("prototype")
static class PrototypeBean {
@Getter
private int count = 0;
public void addCount() {
count++;
}
@PostConstruct
public void init() {
System.out.println(this.getClass().getSimpleName() + " init... " + this);
}
@PreDestroy
public void destroy() {
System.out.println(this.getClass().getSimpleName() + " destroy");
}
}
@Test
void singleTonBeanUsePrototypeBean() {
ConfigurableApplicationContext applicationContext
= new AnnotationConfigApplicationContext(SingletonBean.class, PrototypeBean.class);
SingletonBean singletonBean = applicationContext.getBean(SingletonBean.class);
assertThat(singletonBean.logic()).isEqualTo(1);
SingletonBean singletonBean2 = applicationContext.getBean(SingletonBean.class);
assertThat(singletonBean2.logic()).isEqualTo(2);
applicationContext.close();
}
}