Skip to content
Advertisement

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

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

Advertisement

Answer

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.”

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement