-
Notifications
You must be signed in to change notification settings - Fork 4
/
BeanLocator.java
52 lines (44 loc) · 1.98 KB
/
BeanLocator.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
package com.github.fridujo.automocker.api.tools;
import com.google.common.base.Joiner;
import org.springframework.context.ApplicationContext;
import java.util.Map;
import java.util.stream.Collectors;
public class BeanLocator {
private final ApplicationContext applicationContext;
public BeanLocator(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
/**
* @throws IllegalArgumentException when zero or more than one beans matches
*/
public <T> T getBean(Class<T> beanClass) throws IllegalArgumentException {
Map<String, T> matchingBeansByName = applicationContext.getBeansOfType(beanClass);
return getOnlyOneOrThrow(beanClass.getSimpleName(), matchingBeansByName);
}
/**
* @throws IllegalArgumentException when zero or more than one beans matches
*/
public <T> T getBeanByPartialName(String partialName, Class<T> beanClass) {
Map<String, T> matchingBeansByName = applicationContext.getBeansOfType(beanClass)
.entrySet()
.stream()
.filter(beanAndName -> beanAndName.getKey().contains(partialName))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
return getOnlyOneOrThrow(beanClass.getSimpleName() + "{name: *" + partialName + "*}", matchingBeansByName);
}
private <T> T getOnlyOneOrThrow(String descriptor, Map<String, T> matchingBeansByName) throws IllegalArgumentException {
if (matchingBeansByName.size() == 1) {
return matchingBeansByName.values()
.iterator()
.next();
} else if (matchingBeansByName.isEmpty()) {
throw new IllegalArgumentException("No bean matching " + descriptor);
} else {
throw new IllegalArgumentException("Multiple beans matching " +
descriptor +
". Available: " +
Joiner.on(", ").join(matchingBeansByName.keySet())
);
}
}
}