Ward
Ward

Reputation: 323

Inject service in another service

I have UserService and MissionService.

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

If yes, what about unit testing?

Upvotes: 30

Views: 32073

Answers (1)

Fabian Damken
Fabian Damken

Reputation: 1517

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

Upvotes: 22

Related Questions