Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring Boot: class with @Service bean bean not found

I have multiple @Service class which implements a class BaseService

In a Controller class,
I want to call a Service class (which implements BaseService) based on a parameter

I’m using a function in Utils and calling it from the Controller class

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public final class Util {
   
   public static BaseService getService(String num){
     AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
     context.refresh();
     if(num == 1){
        return context.getBean(TestService.class);
    }
      return context.getBean(AnotherService.class);
   }
}

My TestService class has an @Service annotation

TestService works if I call it using constructor in the Controller class

@Autowired
public TestController(TestService service){
   this.service = service;
}


service.callMethod(); //This works!!

But if I call the instance using Util class, it gives me No such bean as TestService available

>Solution :

Your AnnotationConfigApplicationContext is initially empty. To quote the documentation: “Create a new AnnotationConfigApplicationContext that needs to be populated through register(java.lang.Class<?>...) calls and then manually refreshed.”

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading