Kumar
Kumar

Reputation: 166

Calling another controller from service class in spring

Is it a good practice to call a @controller class from @service class?

As currently i am directly calling controller from another controller(Spring Boot Project),I am planning to introduce @service layer in between.

Please let me know

Upvotes: 5

Views: 5514

Answers (1)

schrieveslaach
schrieveslaach

Reputation: 1819

I would not call a controller from a service layer directly. You might get circular dependencies.

I would use an observer pattern through dependency injection. When the controller implements an interface, you can autowire it into your service.

public interface Observer {

    void eventHappened();

}

@Controller
public class YourController implements Observer {

}

@Service
public class YourService {

    @Autowired
    private Observer o;

    // call o.eventHappened() somewhere in your code
}

If your controller also has a reference to your service, you might need to use InitializingBean which you can use to register the observer.

Upvotes: 5

Related Questions