如何从 Spring 获取实例化 bean 的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14829258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get a list of instantiated beans from Spring?
提问by Aaron Digulla
I have several beans in my Spring context that have state, so I'd like to reset that state before/after unit tests.
我的 Spring 上下文中有几个具有状态的 bean,因此我想在单元测试之前/之后重置该状态。
My idea was to add a method to a helper class which just goes through all beans in the Spring context, checks for methods that are annotated with @Beforeor @Afterand invoke them.
我的想法是向一个辅助类添加一个方法,该类只遍历 Spring 上下文中的所有 bean,检查用@Beforeor注释的方法@After并调用它们。
How do I get a list of instantiatedbeans from the ApplicationContext?
如何获取列表实例化从豆ApplicationContext?
Note: Solutions which simply iterate over all defined beans are useless because I have many lazy beans and some of them must not be instantiated because that would fail for some tests (i.e. I have a beans that need a java.sql.DataSourcebut the tests work because they don't need that bean).
注意:简单地迭代所有定义的 bean 的解决方案是无用的,因为我有很多惰性 bean,其中一些必须不能实例化,因为这会导致某些测试失败(即我有一个需要 a 的 bean,java.sql.DataSource但测试工作,因为它们没有)不需要那个豆子)。
回答by Jose Luis Martin
For example:
例如:
public static List<Object> getInstantiatedSigletons(ApplicationContext ctx) {
List<Object> singletons = new ArrayList<Object>();
String[] all = ctx.getBeanDefinitionNames();
ConfigurableListableBeanFactory clbf = ((AbstractApplicationContext) ctx).getBeanFactory();
for (String name : all) {
Object s = clbf.getSingleton(name);
if (s != null)
singletons.add(s);
}
return singletons;
}
回答by Japan Trivedi
I am not sure whether this will help you or not.
我不确定这是否会对您有所帮助。
You need to create your own annotation eg. MyAnnot. And place that annotation on the class which you want to get. And then using following code you might get the instantiated bean.
您需要创建自己的注释,例如。我的注释。并将该注释放在您想要获取的类上。然后使用以下代码,您可能会获得实例化的 bean。
ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
scanner.addIncludeFilter(new AnnotationTypeFilter(MyAnnot.class));
for (BeanDefinition beanDefinition : scanner.findCandidateComponents("com.xxx.yyy")){
System.out.println(beanDefinition.getBeanClassName());
}
This way you can get all the beans having your custom annotation.
通过这种方式,您可以获得具有自定义注释的所有 bean。
回答by Stefan K.
I had to improve it a little
我不得不稍微改进一下
@Resource
AbstractApplicationContext context;
@After
public void cleanup() {
resetAllMocks();
}
private void resetAllMocks() {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
for (String name : context.getBeanDefinitionNames()) {
Object bean = beanFactory.getSingleton(name);
if (Mockito.mockingDetails(bean).isMock()) {
Mockito.reset(bean);
}
}
}
回答by Velu
applicationContext.getBeanDefinitionNames()does notshow the beans which are registered withoutBeanDefinition instance.
applicationContext.getBeanDefinitionNames()并没有显示其注册的豆子没有的BeanDefinition实例。
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);
}
}
}
}
Console Output
控制台输出
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
As you can see in the output, environment, systemProperties, systemEnvironmentbeans will notbe shown using context.getBeanDefinitionNames()method.
正如您在输出中看到的那样,环境、systemProperties、systemEnvironmentbean 将不会使用context.getBeanDefinitionNames()方法显示。
Spring Boot
弹簧靴
For spring boot web applications, all the beans can be listed using the below endpoint.
对于 Spring Boot Web 应用程序,可以使用以下端点列出所有 bean。
@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.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory", "org.springframework.boot.autoconfigure.condition.BeanTypeRegistry", "org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry", "propertySourcesPlaceholderConfigurer", "org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store", "preserveErrorControllerTargetClassPostProcessor", "org.springframework.context.annotation.internalAutowiredAnnotationProcessor", "org.springframework.context.annotation.internalRequiredAnnotationProcessor", "org.springframework.context.annotation.internalCommonAnnotationProcessor", "org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor", "org.springframework.scheduling.annotation.ProxyAsyncConfiguration", "org.springframework.context.annotation.internalAsyncAnnotationProcessor", "methodValidationPostProcessor", "embeddedServletContainerCustomizerBeanPostProcessor", "errorPageRegistrarBeanPostProcessor", "messageSource", "applicationEventMulticaster", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat", "tomcatEmbeddedServletContainerFactory", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration", "websocketContainerCustomizer", "spring.http.encoding-org.springframework.boot.autoconfigure.web.HttpEncodingProperties", "org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration", "localeCharsetMappingsCustomizer", "org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration", "serverProperties", "duplicateServerPropertiesDetector", "spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration", "conventionErrorViewResolver", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration", "errorPageCustomizer", "servletContext", "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", "requestContextFilter", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration", "hiddenHttpMethodFilter", "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "org.springframework.boot.autoconfigure.AutoConfigurationPackages", "org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$Hymanson2ObjectMapperBuilderCustomizerConfiguration", "spring.Hymanson-org.springframework.boot.autoconfigure.Hymanson.HymansonProperties", "standardHymansonObjectMapperBuilderCustomizer", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperBuilderConfiguration", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration", "jsonComponentModule", "HymansonObjectMapperBuilder", "org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperConfiguration", "HymansonObjectMapper", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration", "org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration", "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration", "error", "beanNameViewResolver", "errorAttributes", "basicErrorController", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter", "mvcContentNegotiationManager", "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration", "stringHttpMessageConverter", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration$MappingHymanson2HttpMessageConverterConfiguration", "mappingHymanson2HttpMessageConverter", "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration", "messageConverters", "mvcConversionService", "mvcValidator", "requestMappingHandlerAdapter", "mvcResourceUrlProvider", "requestMappingHandlerMapping", "mvcPathMatcher", "mvcUrlPathHelper", "viewControllerHandlerMapping", "beanNameHandlerMapping", "resourceHandlerMapping", "defaultServletHandlerMapping", "mvcUriComponentsContributor", "httpRequestHandlerAdapter", "simpleControllerHandlerAdapter", "handlerExceptionResolver", "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.SpringApplicationAdminJmxAutoConfiguration", "springApplicationAdminRegistrar", "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties", "org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration", "multipartResolver", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration$RestTemplateConfiguration", "restTemplateBuilder", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration", "spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration", "fileSystemWatcherFactory", "classPathRestartStrategy", "classPathFileSystemWatcher", "hateoasObjenesisCacheDisabler", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration$LiveReloadServerConfiguration", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$LiveReloadConfiguration", "optionalLiveReloadServer", "org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration", "lifecycleProcessor" ]
[“autoConfigurationReport”、“springApplicationArguments”、“springBootBanner”、“springBootLoggingSystem”、“environment”、“systemProperties”、“systemEnvironment”、“org.springframework.context.annotation.internalConfigurationAnnotationProcessor”、“org.springframework.boot.autoconfigure. internalCachingMetadataReaderFactory”、“org.springframework.boot.autoconfigure.condition.BeanTypeRegistry”、“org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry”、“propertySourcesPlaceholderConfigurer”、“org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.store” ,”preserveErrorControllerTargetClassPostProcessor", "org.springframework.context.annotation.internalAutowiredAnnotationProcessor", "org.springframework.context.annotation.internalRequiredAnnotationProcessor", "org.springframework.context.annotation.internalCommonAnnotationProcessor", "org.springframework.bootties.context.context.context.annotation.internalRequiredAnnotationProcessor" ConfigurationPropertiesBindingPostProcessor”、“org.springframework.scheduling.annotation.ProxyAsyncConfiguration”、“org.springframework.context.annotation.internalAsyncAnnotationProcessor”、“methodValidationPostProcessor”、“embeddedServletContainerCustomizerBeanPostProcessor”、“errorPageRegistrarBeanPostProcessor”、“messageSource”applicationEventMulticaster", "org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat", "tomcatEmbeddedServletContainerFactory", "org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration$TomcatWebSocketConfiguration", "websocketContainerCustomizer", "spring.http.encoding- org.springframework.boot.autoconfigure.web.HttpEncodingProperties”、“org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration”、“localeCharsetMappingsCustomizer”、“org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration”、“serverProperties”、“ duplicateServerPropertiesDetector", "spring.resources-org.springframework.boot.autoconfigure.web.ResourceProperties", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$DefaultErrorViewResolverConfiguration", "conventionErrorViewResolver", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration", "errorPageCustomizer", "servletContext", " 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", "requestContextFilter", "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration", "hiddenHttpMethodFilter" , "httpPutFormContentFilter", "characterEncodingFilter", "org.springframework.context.event.internalEventListenerProcessor", "org.springframework.context.event.internalEventListenerFactory", "reportGeneratorApplication", "exportController", "exportService", "org.springframework.引导。autoconfigure.AutoConfigurationPackages”、“org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$Hymanson2ObjectMapperBuilderCustomizerConfiguration”、“spring.Hymanson-org.springframework.boot.autoconfigure.Hymanson. HymansonProperties”、“standardHymansonObjectMapperBuilderCustomizer”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration$HymansonObjectMapperBuilderConfiguration”、“org.springframework.boot.autoconfigure.Hymanson.HymansonAutoConfiguration”、“jsonComponentModule”、“HymansonObjectMapperBuilder”、“org.springframework” boot.autoconfigure.Hymanson。HymansonAutoConfiguration$HymansonObjectMapperConfiguration”、“HymansonObjectMapper”、“org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration”、“org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration”、“org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration” , "org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration", "defaultValidator", "org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration", "error", "beanNameViewResolver", "errorAttributes", "basicErrorController" , "org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration"、"org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter"、"mvcContentNegotiationManager"、"org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$StringHttpMessageConverterConfiguration"、"stringHttpMessageConverter"、"org.springframework boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration$MappingHymanson2HttpMessageConverterConfiguration”、“mappingHymanson2HttpMessageConverter”、“org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration”、“messageConverters”、“mvcConversionService”、“mvcValidator”、“requestMappingHandlerAdapter”、“mvcResourceUrlProvider”、“requestMappingHandlerMapping”、“mvcPathMatcher”、“mvcUrlPathHelper”、“viewControllerHandlerMapping”、“beanNameHandlerMapping”、“resourceHandlerMapping”、“defaultServletHandlerMapping”、“mvcUriComponentsContributor”、“httpRequestHandlerException”、“simpleControllerHandlerAdapter” , "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.SpringApplicationAdminJmxAutoConfiguration”、“springApplicationAdminRegistrar” , "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration", "org.springframework.boot.autoconfigure.web.HymansonHttpMessageConvertersConfiguration", "spring.info-org.springframework.boot.autoconfigure.info.ProjectInfoProperties", "org. springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration”、“multipartResolver”、“org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration$RestTemplateConfiguration", "restTemplateBuilder", "org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration", "spring.devtools-org.springframework.boot.devtools.autoconfigure.DevToolsProperties", " org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration$RestartConfiguration”、“fileSystemWatcherFactory”、“classPathRestartStrategy”、“classPathFileSystemWatcher”、“hateoasObjenesisCacheDisabler”、“org.springframework.boot.devtools.autoconfigure.LocalDevloadToolsAutoConfiguration$LiveReloadServer” org.springframework.boot.devtools.autoconfigure。LocalDevToolsAutoConfiguration$LiveReloadConfiguration”、“optionalLiveReloadServer”、“org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration”、“lifecycleProcessor”]
回答by Robert Bain
Using the previous answers, I've updated this to use Java 8 Streams API:
使用以前的答案,我已将其更新为使用 Java 8 Streams API:
@Inject
private ApplicationContext applicationContext;
@Before
public void resetMocks() {
ConfigurableListableBeanFactory beanFactory = ((AbstractApplicationContext) applicationContext).getBeanFactory();
Stream.of(applicationContext.getBeanDefinitionNames())
.map(n -> beanFactory.getSingleton(n))
// My ConfigurableListableBeanFactory isn't compiled for 1.8 so can't use method reference. If yours is, you can say
// .map(ConfigurableListableBeanFactory::getSingleton)
.filter(b -> Mockito.mockingDetails(b).isMock())
.forEach(Mockito::reset);
}
回答by Aaron Digulla
I've created a gist ApplicationContextAwareTestBase.
我创建了一个要点 ApplicationContextAwareTestBase。
This helper class does two things:
这个助手类做了两件事:
It sets all internal fields to null. This allows Java to free memory that isn't used anymore. It's less useful with Spring (the Spring context still keeps references to all the beans), though.
It tries to find all methods annotated with
@Afterin all beans in the context and invokes them after the test.
它将所有内部字段设置为空。这允许 Java 释放不再使用的内存。但是,它对 Spring 不太有用(Spring 上下文仍然保留对所有 bean 的引用)。
它尝试
@After在上下文中的所有 bean 中查找所有注释的方法,并在测试后调用它们。
That way, you can easily reset state of your singletons / mocks without having to destroy / refresh the context.
这样,您可以轻松重置单身人士/模拟的状态,而无需销毁/刷新上下文。
Example: You have a mock DAO:
示例:您有一个模拟 DAO:
public void MockDao implements IDao {
private Map<Long, Foo> database = Maps.newHashMap();
@Override
public Foo byId( Long id ) { return database.get( id ) );
@Override
public void save( Foo foo ) { database.put( foo.getId(), foo ); }
@After
public void reset() { database.clear(); }
}
The annotation will make sure reset()will be called after each unit test to clean up the internal state.
注释将确保reset()在每次单元测试后都会调用以清理内部状态。

