Reputation: 166
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
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