You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot中非托管Bean注入后的容器存储与生命周期等问题咨询

Answers to Your Spring Boot Bean Questions

Let's break down each of your questions clearly, based on how Spring manages beans and the behavior of AutowireCapableBeanFactory:

1) Are manually injected non-managed beans stored in the Spring container?

Nope—here's the key detail: When you use AutowireCapableBeanFactory to autowire an instance of NonmangedBean that you created yourself (like new NonmangedBean()), you're only asking Spring to handle dependency injection and lifecycle callbacks (such as @PostConstruct) on that object.

By default, this process does not register the bean with the Spring application context. The container won't keep track of it unless you explicitly call a registration method like registerSingleton() or (in Spring 5+) registerBean() after processing the bean. That's exactly why your /getBeanNames endpoint doesn't pick it up—it only lists beans that are formally registered in the context.

2) Are these injected beans destroyed immediately after the request finishes?

Spring won't automatically manage the destruction of this bean, because it's not registered in the container. Once the request completes, the NonmangedBean instance becomes eligible for garbage collection just like any regular Java object that's no longer referenced.

Spring also won't trigger any destruction callbacks (like @PreDestroy) on it unless you explicitly call AutowireCapableBeanFactory.destroyBean(yourNonManagedBean) yourself. Otherwise, cleanup is left to the JVM's garbage collector to handle when needed.

3) Is there a problem with my printBeans method? Do I need another way to get the list of Spring beans?

Your method is likely working as intended—but it only shows beans that are registered in the application context (like your ManagedBean annotated with @Component). Methods such as ApplicationContext.getBeanDefinitionNames() or getBeanNamesForType() only return beans that Spring knows about via formal registration (annotations, XML definitions, @Bean methods, or manual registration calls).

If you want to track the NonmangedBean instances you've processed with AutowireCapableBeanFactory, you'll need to maintain your own registry (like a thread-safe Set or List) where you store each instance after processing it. Spring doesn't keep a record of unregistered beans it's injected for you.

Just double-check that your printBeans method isn't accidentally filtering out bean types—but the core issue here is that unregistered beans won't appear in the context's built-in bean lists.

内容的提问来源于stack exchange,提问作者Pratik soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:58:16