在Spring的运行时动态声明Bean [英] dynamically declare beans at runtime in Spring

查看:218
本文介绍了在Spring的运行时动态声明Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道以下情况是否可能.出于测试目的,我希望在应用程序上下文中为不同的测试声明不同的模拟类.这些是使用Jersey REST客户端的验收测试.有没有一种方法可以在运行时动态声明Bean? Spring是否有API允许在加载上下文后更改应用程序上下文?

I am wondering if the following is possible. For testing purposes, I wish for different mock classes to be declared in the application context for different tests. These are acceptance tests, using the Jersey REST client. Is there a way to dynamically declare a bean at runtime? Does Spring have an API to allow changes to the application context after the context has been loaded?

推荐答案

在应用程序上下文中具有不同bean的常见方法是使用配置文件.您可以在以下Spring原始帖子中阅读有关个人资料的信息:

The common way to have different beans in the application context is using profiles. You can read about profiles in the following spring source posts:

  • http://blog.springsource.org/2011/02/14/spring-3-1-m1-introducing-profile
  • http://blog.springsource.org/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles/

关于第一个问题,您可以在运行时通过BeanDefinitionRegistry.registerBeanDefinition()方法声明bean,例如:

About your first question, you can declare beans at runtime via BeanDefinitionRegistry.registerBeanDefinition() method, for example:

  BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(SomeClass.class);
  builder.addPropertyReference("propertyName", "someBean");  // add dependency to other bean
  builder.addPropertyValue("propertyName", someValue);      // set property value
  DefaultListableBeanFactory factory = (DefaultListableBeanFactory) context.getBeanFactory();
  factory.registerBeanDefinition("beanName", builder.getBeanDefinition());

还可以向

context.getBeanFactory().registerSingleton(beanName, singletonObject)

最后,Spring没有提供清除刷新上下文后更改bean的明确方法,但是最常见的方法是:

Finally, Spring don't provides a clear way to change a bean after refreshing the context, but the most common approachs are:

  • 关闭并再次刷新(非常有趣)
  • 使用代理并在运行时交换targetSource:请参阅
  • close and refresh again (obiously)
  • Use a proxy and swap the targetSource at runtime: see Replace spring bean in one context with mock version from another context (for an example).

这篇关于在Spring的运行时动态声明Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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