1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.bremersee.test.beans;
18
19 import java.util.function.Consumer;
20 import org.springframework.beans.BeansException;
21 import org.springframework.beans.factory.NoSuchBeanDefinitionException;
22 import org.springframework.beans.factory.ObjectProvider;
23 import org.springframework.lang.NonNull;
24 import org.springframework.lang.Nullable;
25
26
27
28
29
30
31 public class SimpleObjectProvider<T> implements ObjectProvider<T> {
32
33 private final T provides;
34
35 private final Consumer<T> dependencyConsumer;
36
37
38
39
40
41
42 public SimpleObjectProvider(@Nullable T provides) {
43 this(provides, null);
44 }
45
46
47
48
49
50
51
52
53
54
55 public SimpleObjectProvider(@Nullable T provides, @Nullable Consumer<T> dependencyConsumer) {
56 this.provides = provides;
57 this.dependencyConsumer = dependencyConsumer;
58 }
59
60 private void callConsumer(Consumer<T> originalConsumer) {
61 if (provides == null) {
62 return;
63 }
64 if (dependencyConsumer != null) {
65 dependencyConsumer.accept(provides);
66 } else {
67 originalConsumer.accept(provides);
68 }
69 }
70
71 @NonNull
72 @Override
73 public T getObject(@NonNull Object... objects) throws BeansException {
74 if (provides == null) {
75 throw new NoSuchBeanDefinitionException("Mocked object provider has no bean.");
76 }
77 return provides;
78 }
79
80 @Override
81 public void ifAvailable(@NonNull Consumer<T> dependencyConsumer) throws BeansException {
82 callConsumer(dependencyConsumer);
83 }
84
85 @Override
86 public void ifUnique(@NonNull Consumer<T> dependencyConsumer) throws BeansException {
87 callConsumer(dependencyConsumer);
88 }
89
90 @Override
91 public T getIfAvailable() throws BeansException {
92 return provides;
93 }
94
95 @Override
96 public T getIfUnique() throws BeansException {
97 return provides;
98 }
99
100 @NonNull
101 @Override
102 public T getObject() throws BeansException {
103 if (provides == null) {
104 throw new NoSuchBeanDefinitionException("Mocked object provider has no bean.");
105 }
106 return provides;
107 }
108 }