Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

dynamically declare beans at runtime in Spring

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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());

Is possible also to register a singleton bean instance (already configured) with

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...