Cetak semua kacang musim semi yang dimuat

95

Apakah ada cara untuk mencetak semua kacang pegas yang dimuat saat startup? Saya menggunakan Spring 2.0.

Punter Vicky
sumber

Jawaban:

88

Ya, ApplicationContexthubungi dan hubungi.getBeanDefinitionNames()

Anda bisa mendapatkan konteksnya dengan:

  • menerapkan ApplicationContextAware
  • menyuntikkannya dengan @Inject/ @Autowired(setelah 2.5)
  • menggunakan WebApplicationContextUtils.getRequiredWebApplicationContext(..)

Terkait: Anda juga dapat mendeteksi pendaftaran kacang dengan mendaftarkan BeanPostprocessorkacang. Ini akan diberitahukan untuk setiap kacang.

Bozho
sumber
1
Alasan untuk mengimplementasikan ApplicationContextAwareantarmuka adalah karena kerangka kerja Spring memberinya kesempatan untuk mengakses konteks aplikasi. Anda harus menempatkannya di @Configurationkelas untuk konteks aplikasi yang dimaksudkan.
smwikipedia
Tautan terkait: stackoverflow.com/questions/14829258/…
smwikipedia
1
applicationContext.getBeanDefinitionNames () tidak menampilkan kacang yang didaftarkan tanpa instance BeanDefinition. Anda tidak akan dapat membuat daftar kacang tunggal yang didaftarkan secara manual. ex- :) Anda tidak dapat membuat daftar environment, systemProperties, systemEnvironment kacang. Namun kacang ini tersedia di dalam wadah. Anda dapat autowire mereka menggunakan @Auwired Lingkungan env dll stackoverflow.com/a/54863282/1840774
Velu
67
public class PrintBeans {
    @Autowired
    ApplicationContext applicationContext;

    public void printBeans() {
        System.out.println(Arrays.asList(applicationContext.getBeanDefinitionNames()));
    }
}
Akceptor
sumber
applicationContext.getBeanDefinitionNames () tidak menampilkan kacang yang didaftarkan tanpa instance BeanDefinition. Anda tidak akan dapat membuat daftar kacang tunggal yang didaftarkan secara manual. ex- :) Anda tidak dapat membuat daftar environment, systemProperties, systemEnvironment kacang. Namun kacang ini tersedia di dalam wadah. Anda dapat autowire mereka menggunakan @Auwired Lingkungan env dll stackoverflow.com/a/54863282/1840774
Velu
22

Cetak semua nama kacang dan kelasnya:

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";
    }
}
vanfgh
sumber
1
applicationContext.getBeanDefinitionNames () tidak menampilkan kacang yang didaftarkan tanpa instance BeanDefinition. Anda tidak akan dapat membuat daftar kacang tunggal yang didaftarkan secara manual. ex- :) Anda tidak dapat membuat daftar environment, systemProperties, systemEnvironment kacang. Namun kacang ini tersedia di dalam wadah. Anda dapat autowire mereka menggunakan @Auwired Lingkungan env dll stackoverflow.com/a/54863282/1840774
Velu
19

Dengan Spring Boot dan starter aktuator

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

Anda dapat memeriksa titik akhir /beans

vietnem
sumber
2
Pertanyaannya adalah untuk Spring 2.0, bukan Spring Boot.
TMN
8

applicationContext.getBeanDefinitionNames () tidak tidak menunjukkan kacang yang terdaftar tanpa BeanDefinition misalnya.

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);
    }       
}

}


Output Konsol

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

Seperti yang Anda lihat di output, environment, systemProperties, bean systemEnvironment tidak akan ditampilkan menggunakan metode context.getBeanDefinitionNames () .

Boot Musim Semi

Untuk aplikasi web boot musim semi, semua kacang dapat didaftarkan menggunakan titik akhir di bawah ini.

@RestController
@RequestMapping("/list")
class ExportController {

@Autowired
private ApplicationContext applicationContext;

@GetMapping("/beans")
@ResponseStatus(value = HttpStatus.OK)
String[] registeredBeans() {
    return printBeans();
}

private String[] printBeans() {
    AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
    if (autowireCapableBeanFactory instanceof SingletonBeanRegistry) {
        String[] singletonNames = ((SingletonBeanRegistry) autowireCapableBeanFactory).getSingletonNames();
        for (String singleton : singletonNames) {
            System.out.println(singleton);
        }
        return singletonNames;
    }
    return null;
}

}


["autoConfigurationReport", "springApplicationArguments", "springBootBanner", "springBootLoggingSystem", "environment", "systemProperties", "systemEnvironment", "org.springframework.context.annotation.internalConfigurationAnnotationProcessor", "org.spring.framnotationProcessor", "org.spring.framnotationProcessor" internalCachingMetadataReaderFactory "," org.springframework.boot.autoconfigure.condition.BeanTypeRegistry "," org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry "," propertySourcesPlaceholderConfigurer "," propertySourcesPlaceholderConfigurer "org.properties.configurer , "preservErrorControllerTargetClassPostProcessor "," org.springframework.context.annotation.internalAutowiredAnnotationProcessor "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.spring.processorties "," org.springframework.context.annotation.internalRequiredAnnotationProcessor "," org.spring. ConfigurationPropertiesBindingPostProcessor "," org.springframework.scheduling.annotation.ProxyAsyncConfiguration "," org.springframework.context.annotation.internalAsyncAnnotationProcessor "," methodValidationPostProcessor "," embeddedServletContainerCustomizerBeanPostPro "," embeddedServletContainerCustomizerBeanPostource "applicationEventMulticaster "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration $ EmbeddedTomcat "," tomcatEmbeddedServletContainerFactory "," org.springframework.boot.autoconfigure.websocket.WebSocketCutoConfiguration ", spring.websocket.WebSocketCutoConfiguration org.springframework.boot.autoconfigure.web.HttpEncodingProperties "," org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration "," localeCharsetMappingsCustomizer "," org.springframework.boot.autoconfigure.webuto.ServerPropertiesA "," serverPropertiesA " duplikatServerPropertiesDetector "," spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties "," org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ DefaultErrorViewResolverConfiguration "," conventionErrorViewResolver "," org.springframework.boot.autoconfigure.web.ErrorMvcA " contextParameters "," contextAttributes "," spring.mvc-org.springframework.boot.autoconfigure.web.WebMvcProperties "," spring.http.multipart-org.springframework.boot.autoconfigure.web.MultipartProperties "," org.springframework. boot.autoconfigure.web.MultipartAutoConfiguration "," multipartConfigElement "," org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration $ DispatcherServletRegistrationConfiguration "," org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration $ DispatcherServletConfiguration "," dispatcherServlet "," dispatcherServletRegistration " , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "exportController" boot.autoconfigure.AutoConfigurationPackages "," org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ Jackson2.springMapperBuilderCustomizerConfigure.jackson. JacksonProperties "," standardJacksonObjectMapperBuilderCustomizer "," org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperBuilderConfiguration "," org.springframework.booton.autoconfigure.jackson.Jackson.bootonfigure.jackson boot.autoconfigure.jackson.JacksonAutoConfiguration $ JacksonObjectMapperConfiguration "," jacksonObjectMapper "," org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration "," org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration" org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration " , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration $ WhitelabelErrorViewConfiguration", "error", "beanNameViewConfiguration", "error" basic , "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ EnableWebMvcConfiguration "," org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter "," mvcContentNegotiationManager "," org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter "," mvcContentNegotiationManager "," org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter "," mvcContentNegotiationManager "," org.springframework.boot. boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration $ MappingJackson2HttpMessageConverterConfiguration "," mappingJackson2HttpMessageConverter "," org.springframework.boot.autoconfigure.web.HttpMessageConvertersAuto "," pesan "mVVConvertersAuto", "migurationConvertersAutoConfigurationrequestMappingHandlerAdapter "," mvcResourceUrlProvider "," requestMappingHandlerMapping "," mvcPathMatcher "," mvcUrlPathHelper "," viewControllerHandlerMapping "," beanNameHandlerMapping "," resourceHandlerMapping "defaultServroller", "resourceHandlerMapping" defaultServroller "," resourceHandlerMapping "defaultServlet", "simple" httpRvcUequroller "," simple "dan" httpRvcUequroller "," sederhana "beanNameHandlerMapping" , "mvcViewResolver", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration $ WebMvcAutoConfigurationAdapter $ FaviconConfiguration", "faviconRequestHandler", "faviconHandlerMapping", "defaultViewResolver", "viewResolver "," welcomePageHandlerMapping "," org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration "," objectNamingStrategy "," mbeanServer "," mbeanExporter "," org.springframework.boot.autoconfigure.admin.SpringApplication "," springminConfiguration " , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.JacksonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.Properties" springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration "," multipartResolver "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration $ RestTemplateConfiguration "," restTemplateBuilder "," org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration "," spring.devtools-org.springframework.TautocProperties "," spring.devtools-org. org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration $ RestartConfiguration "," fileSystemWatcherFactory "," classPathRestartStrategy "," classPathFileSystemWatcher "," hateoasObautocigurevigureRonfigureRoadfools.sistemFiguration LiveDisonfiguration LiveConfiguration org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration $ LiveReloadConfiguration "," optionalLiveReloadServer "," org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration "," lifecycleProcessor "]

Velu
sumber
6

Anda bisa mencoba menelepon

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

Atau aktifkan logging debug untuk org.springframework. (Di boot musim semi, itu menggunakan parameter --logging.level.org.springframework=DEBUG)

artbristol
sumber
ListableBeanFactoryadalah sebuah antarmuka. Di mana seseorang akan mendapatkan instance dari kelas yang memperluas antarmuka itu untuk mengeksekusi metode getBeansOfTypeatau metode lain di antarmuka? Saya melihat itu ApplicationContextmemperluasnya, tetapi contoh Anda tidak menunjukkan bagaimana mendapatkan salah satunya.
ErikE
Anda cukup menambahkan bidang @Autowired ListableBeanFactory listableBeanFactorydan Anda akan mendapatkannya (jenis penerapan seharusnya tidak menjadi masalah)
artbristol
1

Menggunakan spring-boot-starter-actuatorAnda dapat dengan mudah mengakses semua kacang.

Berikut proses penyiapannya:

  1. Tambahkan ketergantungan ke gradle :

Tambahkan di bawah ke file gradle:

compile("org.springframework.boot:spring-boot-starter-actuator")
  1. Aktifkan keamanan di application.properties :

Tambahkan management.security.enabled=falseke file application.property Anda

  1. call / beans endpoint :

    Setelah penyiapan itu, musim semi akan mengaktifkan beberapa titik akhir terkait metrik. Salah satu titik akhirnya adalah / beans Setelah memanggil endpoint ini, ia akan menyediakan file json yang berisi semua bean Anda termasuk dependensi dan cakupannya.

Berikut ini contoh file 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":[]}]

Untuk info lebih lanjut kunjungi tautan di bawah:

Semoga ini bisa membantu Anda. Terima kasih :)

Md. Sajedul Karim
sumber
1
musim semi! = sepatu bot musim semi
Himanshu Bhardwaj
Ya, itu benar saudara :). Solusi ini untuk sprint boot.
Md. Sajedul Karim
1

Berikut adalah cara lain untuk mencetak semua nama kacang dari konteks aplikasi pegas:

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 ****************** 
Ved Singh
sumber