Home » Java » Java Spring Adding or removing @Component at runtime is possible?-Exceptionshub

Java Spring Adding or removing @Component at runtime is possible?-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Hi i have something like this.

@Component public class JohnStephen
@Component public class Guadalupe
@Component public class CristianOrtiz
@Component public class CristinaCuellar
/*AND SO ON*/

All the profiles are creating all the beans because all the beans can be used on each environment.

I have over 1000 beans created right? but i did realize that i need just one on each application startup is required i mean i know which of them is required and i can pass that info on the JVM vm_options something like this.

vm-options beanToCreate=CristianOrtiz

On this info i would like that CristianOrtiz only is set as a bean and not the others can this be done in any way in spring??

How to&Answers:

You could use spring profiles to switch these on and of at startup but not at runtime.

Annotate each of these Components with @Profile("profileName") and activate them with -Dspring.profiles.active=profileName as a commandline parameter.

Further reading:
– a nice primer on baeldung