java 以编程方式设置特定的 bean 对象 - Spring DI

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1092423/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:09:25  来源:igfitidea点击:

Programmatically set a specific bean object - Spring DI

javaspringdependency-injection

提问by Itay Maman

In my program I need to programmatically configure an ApplicationContext. Specifically, I have a reference to an instance of MyClass and I want to define it as a new bean called "xxyy".

在我的程序中,我需要以编程方式配置一个 ApplicationContext。具体来说,我有一个对 MyClass 实例的引用,我想将它定义为一个名为“xxyy”的新 bean。

public void f(MyClass mc, ApplicationContext ac) {
  // define mc as the "xxyy" bean on ac ???
  ...
  ...

  // Now retrieve that bean
  MyClass bean = (MyClass) ac.getBean("xxyy");

  // It should be the exact same object as mc
  Assert.assertSame(mc, bean); 
}

The BeanDefinition API let's me specify the class of the new bean, so it does not work for me since I want to specify the instance. I managed to find a solution but it took two additional factory beans which seems like too much code for such an eartly purpose.

BeanDefinition API 让我指定新 bean 的类,所以它对我不起作用,因为我想指定实例。我设法找到了一个解决方案,但它使用了两个额外的工厂 bean,对于这样一个早期的目的来说,这似乎是太多的代码。

Is there a standard API that addresses my needs?

是否有满足我需求的标准 API?

回答by silmx

you can use this context:

你可以使用这个上下文:

GenericApplicationContext mockContext = new GenericApplicationContext();

which has a

其中有一个

mockContext.getBeanFactory().registerSingleton("name", reference);

and plug it in the real context

并将其插入真实上下文中

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "real-context.xml" }, mockContext);

and the classes are:

课程是:

import org.springframework.context.support.ClassPathXmlApplicationContext;

import org.springframework.context.support.GenericApplicationContext;

回答by skaffman

You need to jump through a few hoops to do this. The first step is to obtain a reference to the context's underlying BeanFactory implementation. This is only possible if your context implements ConfigurableApplicationContext, which most of the standard ones do. You can then register your instance as a singleton in that bean factory:

你需要跳过几圈才能做到这一点。第一步是获取对上下文的底层 BeanFactory 实现的引用。这只有在您的上下文实现 ConfigurableApplicationContext 时才有可能,大多数标准上下文都这样做。然后,您可以在该 bean 工厂中将您的实例注册为单例:

ConfigurableApplicationContext configContext = (ConfigurableApplicationContext)appContext;
SingletonBeanRegistry beanRegistry = configContext.getBeanFactory();
beanRegistry.registerSingleton("xxyy", bean);

You can "insert" any object into the context like this.

您可以像这样将任何对象“插入”到上下文中。