Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject service in another service

Tags:

I have UserService and MissionService.

Is it ok to inject MissionService in UserSerivce or vice versa?

If yes, what about unit testing?

like image 567
Ward Avatar asked Aug 13 '16 15:08

Ward


People also ask

Is it possible to inject another service into a service?

Yes, the first thing is to add the @Injectable decorator on each services you want to inject. In fact, the Injectable name is a bit insidious. It doesn't mean that the class will be "injectable" but it will decorate so the constructor parameters can be injected.

Can we call a service from another service in Angular?

Angular Service that needs another service You don't have to do much to configure dependency between services. A service that needs another service should have a @Injectable decorator and then you can apply the same constructor injection pattern where you provide the service dependency with in the constructor.

How do you inject a service into a component?

Angular provides the ability for you to inject a service into a component to give that component access to the service. The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency.

Is it mandatory to have @injectable in service?

The @Injectable decorator is not compulsory to add if you don't use the 'providedIn' option. The @Injectable decorator together with the 'providedIn' option means the service should not be added within the providers' array of a module.


1 Answers

Of course you can and it is perfectly fine. But I recommend that you use method-injection in order to allow you to set the instance at runtime without using using reflection (you can create an instance manually).


For example:

@Service public class MissionService { }  @Service public class UserService {     private MissionService missionService;      @Autowired     public void setMissionService(MissionService missionService) {         this.missionService = missionService;     } } 

This allows you to create both services using regular Java without Spring:

MissionService missionService = new MissioNService(); UserService userService = new UserService(); userService.setMissionService(missionService); 

Caution: You have to take care of not building dependency cycles. It is not set that Spring resolves them, I think

like image 75
Fabian Damken Avatar answered Oct 18 '22 03:10

Fabian Damken