Ward Ward - 1 year ago 153
Java Question

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 ?

Answer Source

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:

public class MissionService { }

public class UserService {
    private MissionService missionService;

    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();

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download