Skip to content

Instantly share code, notes, and snippets.

@skempken
Last active June 15, 2021 15:15
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save skempken/dbb2ad55d213cd6a1f50 to your computer and use it in GitHub Desktop.
Save skempken/dbb2ad55d213cd6a1f50 to your computer and use it in GitHub Desktop.
Find all annotated classes in a package using Spring
import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.web.context.support.StandardServletEnvironment;
public class Detector {
private static final Logger LOGGER = LoggerFactory.getLogger(Detector.class);
public Class<?>[] findAllConfigurationClassesInPackage(String packageName) {
final List<Class<?>> result = new LinkedList<Class<?>>();
final ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
true, new StandardServletEnvironment());
provider.addIncludeFilter(new AnnotationTypeFilter(Configuration.class));
for (BeanDefinition beanDefinition : provider
.findCandidateComponents(packageName)) {
try {
result.add(Class.forName(beanDefinition.getBeanClassName()));
} catch (ClassNotFoundException e) {
LOGGER.warn(
"Could not resolve class object for bean definition", e);
}
}
return result.toArray(new Class<?>[result.size()]);
}
}
@jrichardsz
Copy link

Thanks, worked at first attempt!!
I parametrized the class:

https://gist.github.com/jrichardsz/a34480c1bcc31c45da730c48c4f41331

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment