何时将参数作为构造函数参数或方法参数传递
我目前有一个在类方法中使用 Service 类的类。目前,我正在我的方法中创建服务类的实例,如下所示。我想知道的问题是,在测试时,我使用的是 spock,当在方法中创建类的新实例而不是作为依赖注入的构造函数参数传入时,似乎很难测试。我想知道将 Service 类的实例作为构造函数参数传递到 Handler 中是否是执行此操作的正确方法?谢谢
public class Handler{
private Service service;
public Handler(){}
public void someMethod(ObjectNeededForService object){
service = new Service(object);
}
}
I currently have this class that uses a Service class in a class method. Currently I am creating an instance of the service class in my method as shown below. The question I am wondering is that when it comes to testing, I am using spock and it seems to be difficult to test when a new instance of a class is being created in the method rather than being passed in as a constructor parameter for dependency injection. I am wondering would passing in an instance of Service class into Handler as a constructor parameter be the correct way of doing this? Thanks
public class Handler{
private Service service;
public Handler(){}
public void someMethod(ObjectNeededForService object){
service = new Service(object);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个棘手的问题,您会找到不同的答案。
如果我理解正确的话,您基本上是在问构造函数注入是否比 setter 注入更好,反之亦然,对吗?
显然,当类中的字段数量有限时,构造函数注入会很方便。具有 20 个参数的构造函数可读性不太好,绝对应该避免。在这种情况下,您将必须使用 setter 注入并一一调用各个字段的 setter。
但是,如果您有一个包含如此多需要注入的字段的类,那么最好进行重构并将依赖项减少到较小的数量。
就我个人而言,我更喜欢构造函数注入,但也有人反对它。
This is a tricky question and you'll find different answers for that.
If I understand correctly, you are basically asking if constructor injection is better than setter injection or vice versa, correct?
Obviously constructor injection is neat when you have a limited amount of fields in your class. Constructors with 20 args are not very readable and should definitely be avoided. In that case you would have to use setter injection and call the setters for the individual fields one by one.
But maybe if you have a class with so many fields that need injecting, it would be good to refactor and get your dependencies down to a smaller amount.
Personally I prefer construtor injection but there are arguments against it.