java 在另一个服务中注入服务
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38934365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Inject service in another service
提问by Ward
I have UserService and MissionService.
我有 UserService 和 MissionService。
Is it ok to inject MissionService in UserSerivce or vice versa?
在 UserSerivce 中注入 MissionService 是否可以,反之亦然?
If yes, what about unit testing?
如果是,那么单元测试呢?
采纳答案by Fabian Damken
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:
这允许您在没有 Spring 的情况下使用常规 Java 创建这两种服务:
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
注意:您必须注意不要构建依赖循环。我认为 Spring 并没有解决它们