打印加载的所有Spring bean

velaa5lx  于 2023-04-04  发布在  Spring
关注(0)|答案(8)|浏览(185)

有没有办法打印启动时加载的所有springbean?我使用的是Spring2.0。

dgiusagp

dgiusagp1#

是,联系ApplicationContext并呼叫.getBeanDefinitionNames()
您可以通过以下方式获取上下文:

  • 实现ApplicationContextAware
  • 注射@Inject/@Autowired(2.5后)
  • 使用WebApplicationContextUtils.getRequiredWebApplicationContext(..)

相关:您还可以通过注册BeanPostprocessor bean来检测每个bean的注册。它将为每个bean发出通知。

ajsxfq5m

ajsxfq5m2#

public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}
wkftcu5l

wkftcu5l3#

带 Spring Boot 和致动器起动器

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

可以检查端点/beans

lztngnrs

lztngnrs4#

打印所有bean名称及其类:

package com.javahash.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloWorldController {

    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("/hello")
    public String hello(@RequestParam(value="key", required=false, defaultValue="World") String name, Model model) {

        String[] beanNames = applicationContext.getBeanDefinitionNames();

        for (String beanName : beanNames) {

            System.out.println(beanName + " : " + applicationContext.getBean(beanName).getClass().toString());
        }

        model.addAttribute("name", name);

        return "helloworld";
    }
}
xkftehaa

xkftehaa5#

applicationContext.getBeanDefinitionNames()显示注册没有**BeanDefinition示例的bean。

package io.velu.core;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
public class Core {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Core.class);
        String[] singletonNames = context.getDefaultListableBeanFactory().getSingletonNames();
        for (String singleton : singletonNames) {
            System.out.println(singleton);
        }       
    }
}

控制台输出

environment
systemProperties
systemEnvironment
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
messageSource
applicationEventMulticaster
lifecycleProcessor

在输出中可以看到,使用context.getBeanDefinitionNames()方法,environment,systemProperties,systemEnvironmentbeans将显示。

Sping Boot

对于Sping Boot Web应用程序,可以使用下面的端点列出所有bean。
一个二个一个一个

ct2axkht

ct2axkht6#

你可以打电话试试

org.springframework.beans.factory.ListableBeanFactory.getBeansOfType(Object.class)

或者打开org.springframework的调试日志(在spring Boot 中,使用参数--logging.level.org.springframework=DEBUG

dgjrabp2

dgjrabp27#

下面是从spring application context打印所有bean名称的另一种方法:

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/***********************************************************************************************************
 * Java File: MainApplication.java
 * Description: Main class to run the application.
 * 
 ***********************************************************************************************************/

@SpringBootApplication
public class MainApplication {

private static final Logger logger = LogManager.getLogger(MainApplication.class);

public static void main(String[] args) 
{
    final ConfigurableApplicationContext context = SpringApplication.run(MainApplication.class, args);

    final AtomicInteger counter = new AtomicInteger(0);
    logger.info("**************** START: Total Bean Objects: {} ******************", context.getBeanDefinitionCount());

    Arrays.asList(context.getBeanDefinitionNames())
    .forEach(beanName -> {
        logger.info("{}) Bean Name: {} ", counter.incrementAndGet(), beanName);
    });

    logger.info("**************** END: Total Bean: {} ******************", context.getBeanDefinitionCount());
}

}

Sample Output:

2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:18] - **************** START: Total Bean Objects: 564 ****************** 
...........................
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 460) Bean Name: mvcPathMatcher  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 461) Bean Name: mvcUrlPathHelper  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 462) Bean Name: viewControllerHandlerMapping  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 463) Bean Name: beanNameHandlerMapping  
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:22] - 464) Bean Name: resourceHandlerMapping 
...........................
2019-11-27 20:08:02.821 INFO  [main] [c.c.a.MainApplication:25] - **************** END: Total Bean: 564 ******************
dtcbnfnu

dtcbnfnu8#

使用spring-boot-starter-actuator可以轻松访问所有bean。
以下是设置过程:
1.在gradle中添加依赖
将以下文件添加到gradle文件中:

compile("org.springframework.boot:spring-boot-starter-actuator")

1.开启www.example.comapplication.properties安全
management.security.enabled=false添加到application.property文件中
1.call /beans端点
在此设置之后,spring将启用一些与指标相关的端点。它的一个端点是**/beans**在调用此端点之后,它将提供一个json文件,其中包含所有bean,包括其依赖项和范围。
下面是一个json文件的例子:

[{"context":"application:8442","parent":null,"beans":[{"bean":"beanName","aliases":[],"scope":"singleton","type":"packageName$$4b46c703","resource":"null","dependencies":["environment","beanName1","beanName2"]},{"bean":"org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory","aliases":[],"scope":"singleton","type":"org.springframework.core.type.classreading.CachingMetadataReaderFactory","resource":"null","dependencies":[]}]

欲了解更多信息,请访问以下链接:

希望这对你有帮助。谢谢:)

相关问题