如何在spring boot中使用应用程序上下文获取bean
我正在开发一个spring boot项目,我希望使用applicationContext
来获取bean的名称。 我在网上尝试了很多解决方案,但无法成功。 我的要求是我有一个控制器
ControllerA
并且内部控制器ai有一个方法getBean(String className)
,我想获取已注册bean的实例。 我有hibernate实体,我想通过仅在getBean
方法中传递类的名称来获取bean的实例。
如果有人知道解决方案,请帮忙
您可以将ApplicationContext自动assembly为字段
@Autowired private ApplicationContext context;
或方法
@Autowired public void context(ApplicationContext context) { this.context = context; }
最后用
context.getBean(SomeClass.class)
您可以使用ApplicationContextAware 。
ApplicationContextAware :
希望被通知其运行的ApplicationContext的任何对象实现的接口。例如,当一个对象需要访问一组协作bean时,实现此接口是有意义的。
有几种方法可以获得对应用程序上下文的引用。 您可以实现ApplicationContextAware,如以下示例所示:
package hello; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; @Component public class ApplicationContextProvider implements ApplicationContextAware { private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public ApplicationContext getContext() { return applicationContext; } }
更新:
当Spring实例化bean时 ,它会查找ApplicationContextAware实现,如果找到它们,将调用setApplicationContext()方法。
通过这种方式,Spring正在设置当前的 applicationcontext。
Spring source code
代码片段:
private void invokeAwareInterfaces(Object bean) { ..... ..... if (bean instanceof ApplicationContextAware) { ((ApplicationContextAware)bean).setApplicationContext(this.applicationContext); } }
一旦获得对Application上下文的引用,就可以使用getBean()获取所需的bean。
实际上你想从Spring引擎中获取对象,其中引擎已经在spring应用程序的初始化(Sprint引擎的初始化)中维护了所需类的对象。现在你必须得到那个对象一个参考。
在服务类中
@Autowired private ApplicationContext context; SomeClass sc = (SomeClass)context.getBean(SomeClass.class);
现在在sc的引用中你有了对象。 希望解释得很好。 如有任何疑问请告诉我。
如果你在Spring bean里面(在这种情况下是@Controller
bean)你根本不应该使用Spring上下文实例。 直接自动assemblyclassName
bean。
顺便说一句,避免使用现场注射,因为它被认为是不好的做法。
您可以使用ServiceLocatorFactoryBean。 首先,您需要为您的class级创建一个界面
public interface YourClassFactory { YourClass getClassByName(String name); }
然后,您必须为ServiceLocatorBean创建配置文件
@Configuration @Component public class ServiceLocatorFactoryBeanConfig { @Bean public ServiceLocatorFactoryBean serviceLocatorBean(){ ServiceLocatorFactoryBean bean = new ServiceLocatorFactoryBean(); bean.setServiceLocatorInterface(YourClassFactory.class); return bean; } }
现在,您可以按名称找到您的class级
@Autowired private YourClassfactory factory; YourClass getYourClass(String name){ return factory.getClassByName(name); }