
com.github.fridujo.automocker.api.tools.BeanLocator Maven / Gradle / Ivy
The newest version!
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 getBean(Class beanClass) throws IllegalArgumentException {
Map matchingBeansByName = applicationContext.getBeansOfType(beanClass);
return getOnlyOneOrThrow(beanClass.getSimpleName(), matchingBeansByName);
}
/**
* @throws IllegalArgumentException when zero or more than one beans matches
*/
public T getBeanByPartialName(String partialName, Class beanClass) {
Map 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 getOnlyOneOrThrow(String descriptor, Map 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())
);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy