Creating Spring Bean dynamically in the Runtime
After 5 years it seems that this article in my blog is the most popular one, over 9,300 page views. So, it’s time to update this article. I also added a Github example for this article.
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 properties 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:
@Service
public class CustomerServiceImpl { private Customer dynamicCustomerWithAspect;
@InjectDynamicObject
public Customer getDynamicCustomerWithAspect() {
return this.dynamicCustomerWithAspect;
}
}
3. Write an aspect with Pointcut and Advise which change the object returned by the method in the step 2:
@Component
@Aspect
public…