Reputation: 605
I am trying to enlist all the beans written by me when I boot up the SpringApplication.
Getting all the beans listed is done. This code does it.
String[] beanNames = appContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
I tried using a basic filter to look for my stuff.
String[] beanNames = appContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
if (beanName.matches("(.*)Controller"))
System.out.println(beanName);
}
But that does not work because when the classes are loaded it is really the bean name that is loaded and not the exact name of the classes. So if I wrote a my.personal.package.structure.MyController it would most probably show up as myController. The package structure information is lost rendering this technique, not quite effective.
Has anyone tried some other way that worked. I expect this to be very handy for a developer for debugging.
Upvotes: 2
Views: 2525
Reputation: 16086
Using ConfigurableApplicationContext
you can get all bean types. For example:
@Autowired
ConfigurableApplicationContext context;
.....
ConfigurableListableBeanFactory beansFactory = context.getBeanFactory();
String[] beansNames = beansFactory.getBeanDefinitionNames();
Set<String> beansType = new HashSet<>();
for(String beanName : beansNames){
if (beanName.matches("(.*)Controller")){
beansType.add(beansFactory.getType(beanName).toString());
}
}
Other easier option to show all the beans is
In the case you are using spring-web You could use Spring boot actuator
. Add the next dependency in your pom.xml
and go to the /bean
endpoint to show all beans, and it will put the name of the bean and the class.
Upvotes: 4