怎么打印springboot中所有bean
时间: 2024-05-15 12:18:57 浏览: 63
springboot 使用上下文获取bean
您可以通过在SpringBoot应用程序中运行以下代码来列出所有Bean:
```java
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class BeanLister {
private final ApplicationContext applicationContext;
public BeanLister(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public void printAllBeanNames() {
String[] beanNames = applicationContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
```
使用该程序的示例方法是:
```java
@SpringBootApplication
public class SpringbootAppApplication implements CommandLineRunner {
private final BeanLister beanLister;
public SpringbootAppApplication(BeanLister beanLister) {
this.beanLister = beanLister;
}
public static void main(String[] args) {
SpringApplication.run(SpringbootAppApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
beanLister.printAllBeanNames();
}
}
```
当Spring命令行运行器运行时,将会打印出所有Bean的名称。
阅读全文