Pun*_*cky 26 spring spring-boot
我怎样才能知道作为我的春季启动应用程序的一部分加载的所有bean的名称?我想在main方法中有一些代码来打印服务器启动后加载的bean的详细信息.
Yan*_*lem 44
如spring-boot的入门指南所示:https://spring.io/guides/gs/spring-boot/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
};
}
}
Run Code Online (Sandbox Code Playgroud)
正如@Velu在评论中提到的,这不会列出手动注册的bean.
如果您想这样做,可以使用getSingletonNames().不过要小心.此方法仅返回已实例化的bean.如果bean尚未实例化,则此方法不会返回它.
Zer*_*leb 18
我建议使用Actuator吗?它提供了几个端点,包括/beans
列出应用程序中的所有bean.您说"一旦服务器启动",因此这是Web应用程序的一个选项.
设置执行器
执行器中的端点列表
http://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html
好吧,虽然这个问题已经得到解答,但我仍然希望提供一个Java 8变体的答案:)
Arrays.asList(context.getBeanDefinitionNames()).stream().sorted().forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
让我们做Java 8 !!!
实际上,除了修改 @SpringBootApplication 之外,我还建议创建此类。
@Component
public class ContextTeller implements CommandLineRunner {
@Autowired
ApplicationContext applicationContext;
@Override
public void run(String... args) throws Exception {
System.out.println("-------------> just checking!");
System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
}}
Run Code Online (Sandbox Code Playgroud)
这样 Spring Boot 将加载此类并在加载上下文后立即执行。然后你只需删除该文件,一切就都清楚了。
归档时间: |
|
查看次数: |
27741 次 |
最近记录: |