Skip to main content

Creating Spring Bean dynamically in the Runtime

In my training someone asked me whether it is possible to create an object (a Spring Bean) dynamically so you can choose which implementation you want to have in the runtime. So at the compile time you don't know what object actually should be created yet. The application should decide what object to be created based on a property file.

1. We create an annotation so we can mark the method which should be able to create the object dynamically:

...
package your.package;
...
@Retention(RetentionPolicy.RUNTIME)
public @interface InjectDynamicObject {
}
...

2. Use the new created annotation in your method which should be able to create the object dynamically:

...
@Named("customerBo")
public class CustomerBoImpl implements CustomerBo {
...
    @Override
  @InjectDynamicObject
  public Customer getDynamicCustomer() {
        return this.dynamicCustomer;
}
...

3. Write an aspect with Pointcut and Advise which change the object returned by the method in the step 2:

...
@Named
@Aspect
public class DynamicObjectAspect {

    // This comes from the property file 
@Value("#{objects.object}")
private String object;

@Inject
private ApplicationContext applicationContext;

@Pointcut("execution(@your.package.InjectDynamicObject * *(..))")
public void beanAnnotatedWithInjectDynamicObject() {
}

@Around("beanAnnotatedWithInjectDynamicObject()")
public Object adviceBeanAnnotatedWithInjectDynamicObject(
ProceedingJoinPoint pjp) throws Throwable {
Object returnResult = pjp.proceed();
       // Create the bean or object depends on the property file
Object createdObject = applicationContext.getBean(object);
return createdObject;
}
}
...

4. Write your unit test to test the method:

...
    @Test
public void testCustomerOnlineOrOffline() {
// Dynamic object creation
System.out.println("DYNAMIC CUSTOMER: "
+ customerBo.getDynamicCustomer().getName());
}
...

OK, there is another easier way to do this ;-) Without Aspects and AspectJ, just pure Spring:

Just inject all your component implementations into a Map and get the correct implementation out of it. Just like what we have done in eXTra Client application. Please take a look at our implementation of PluginsLocatorManager as an example: http://goo.gl/itpcb. Spring injects the Map with Bean name as String and the Bean itself automagically. "... Even typed Maps can be autowired as long as the expected key type is String. The Map values will contain all beans of the expected type, and the keys will contain the corresponding bean names" (see Spring documentation for details).

...
@Named("customerBo")
public class CustomerBoImpl implements CustomerBo {
...
    // We inject the customer implementations into a Map
    @Inject
    private Map<String, Customer> customerDynamicMap;


    // This comes from the property file as a key for the Map
@Value("#{objects.object}")
private String object;
    
    @Override
  public Customer getDynamicCustomer() {
        return this.customerDynamicMap.get(object);
}
...

Have fun!
Lofi

Comments

Manju behera said…
Thanks for this awesome post. I was going through the Github link and found ot that dynamicCustomerWithMap is no where set. Can you please let me know where you are setting values in Map(dynamicCustomerWithMap)?
Prayan Learning said…
Great blog. An important
image annotation technique which outlines the object in the image with a box, for object classification and localization models.
Onlineemenu said…
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog.

Software consultant Company Frisco

Sales Tracking development company

Hire Apple iTv Developers

Hire Certified Hadoop Developers
Village Talkies said…
Informative blog! it was very useful for me.Thanks for sharing. Do share more ideas regularly.
Village Talkies a top-quality professional corporate video production company in Bangalore and also best explainer video company in Bangalore & animation video makers in Bangalore, Chennai, India & Maryland, Baltimore, USA provides Corporate & Brand films, Promotional, Marketing videos & Training videos, Product demo videos, Employee videos, Product video explainers, eLearning videos, 2d Animation, 3d Animation, Motion Graphics, Whiteboard Explainer videos Client Testimonial Videos, Video Presentation and more for all start-ups, industries, and corporate companies. From scripting to corporate video production services, explainer & 3d, 2d animation video production , our solutions are customized to your budget, timeline, and to meet the company goals and objectives.
As a best video production company in Bangalore, we produce quality and creative videos to our clients.
Rahim Ladhani said…
Wow, this is a very interesting reading. I found a lot of things which I need. Great job on this content. Know How Much Does it Cost to Develop a Cryptocurrency Exchange App?

Saba Firdous said…
"Hii I read your article i really appreciate for your work and share your knowlegde with us about software development and I want to say thankyou that you share your thoughts with us keep it up."
Thanks a lot for sharing this amazing blog with us. The entire information is really good. Please keep sharing more blogs like this.
App Development Cost in India
Anil said…
APTRON's Java Course in Gurgaon caters to all levels. With hands-on practical sessions, interactive learning modules, and real-world projects, students gain a deep understanding of Java programming concepts and its application in various industries. Moreover, APTRON's state-of-the-art facilities and supportive learning environment ensure that every student receives personalized attention and guidance throughout their learning journey.
Reapmind said…
Thank you for sharing this incredible blog with us. The entire content is extremely informative and valuable. As a leading mobile app development company , we truly appreciate such insightful articles. Please continue to share more blogs like this in the future

Popular posts from this blog

Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?

Last year we saw the launch of a new Web programming language Dart - Structured Web Programming from Google. A very interesting approach to support web application development. Not so long after Go, Groovy, Ruby, Scala, << name your DSL here >> ; we see Dart. Is it a good thing to have at least one programming language to solve one problem? The answer is, like we already know, it depends. Some important backgrounds you should know about the multi programming language paradigm are following: 1. You can read Martin Fowler article about language oriented programming with language workbenches which enables you to write small programming languages easily. In this article I see everyone writing their small languages, everywhere. In this concept we see DSL (Domain Specific Language) as the future of our programming activities. Source: http://martinfowler.com/articles/languageWorkbench.html 2. Neal Ford talked about Polyglot Programming, combining multiple programming language

Software Development Macro and Micro Process

If you think that in year 2012 all companies which produce software and IT divisions in our world have already their optimized software development process, you are wrong. It seems that we - software architects, software developers or whatever your title is - still need to optimize the software development process in many software companies and IT divisions. So what do you do if you enter a software company or IT division and you see following things: 1. There is a perfect project management process to handle all those development of software but it is a pure project management without a context to software development. So basically you only take care of cost, time, budget and quality factors. In the software development you still use the old fashioned waterfall process. 2. From the tooling point of view: you have a project management planning and controlling tool but you are still in the beginning of Wiki (almost no collaboration tool) and you don't use issues tracking sy