Ward Ward - 3 months ago 15
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

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

Comments