何时将参数作为构造函数参数或方法参数传递

发布于 2025-01-10 16:15:03 字数 371 浏览 0 评论 0原文

我目前有一个在类方法中使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似狗非友 2025-01-17 16:15:04

这是一个棘手的问题,您会找到不同的答案。
如果我理解正确的话,您基本上是在问构造函数注入是否比 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文