如何在 Spring Boot 中使用应用程序上下文获取 bean [英] How to get bean using application context in spring boot

查看:43
本文介绍了如何在 Spring Boot 中使用应用程序上下文获取 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 SpringBoot 项目,我想使用 applicationContext 通过它的名称获取 bean.我从网上尝试了很多解决方案,但都没有成功.我的要求是我有一个控制器

I am developing a SpringBoot project and I want to get the bean by its name using applicationContext. I have tried many solution from web but could not succeed. My Requirement is that I have a controller

ControllerA

在控制器内部我有一个方法getBean(String className).我想获取已注册 bean 的实例.我有休眠实体,我想通过仅在 getBean 方法中传递类的名称来获取 bean 的实例.

and inside the controller I have a method getBean(String className). I want to get instance of registered bean. I have hibernate entities and I want to get an instance of the bean by passing the name of class only in getBean method.

如果有人知道解决方案,请帮忙.

Please help if someone know the solution.

推荐答案

您可以自动装配 ApplicationContext,或者作为一个字段

You can Autowire the ApplicationContext, either as a field

@Autowired
private ApplicationContext context;

或方法

@Autowired
public void context(ApplicationContext context) { this.context = context; }

最后使用

context.getBean(SomeClass.class)

这篇关于如何在 Spring Boot 中使用应用程序上下文获取 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆