注入私人,包裹或公共场地或提供设定者? [英] Inject into private, package or public field or provide a setter?

查看:164
本文介绍了注入私人,包裹或公共场地或提供设定者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到许多使用依赖注入的Java示例,没有公共设置器的私有字段:

I see many Java examples using dependency injection with private fields without a public setter like this:

public SomeClass {
  @Inject
  private SomeResource resource;
}

但是,当注入应手动执行时,这是一个坏主意,例如单元测试。

But that is a bad idea when the injection should be performed manually for example in unit tests.

有几种可能性来解决这个问题:

There are several possibilities to solve this:


  • 添加一个public setter: setSomeResource(SomeResource r)

  • 使该字段为public

  • 包保护

我想避免设置者,因为没有真正发生的事情。所以我更喜欢public或package protected。你有什么建议?

I'd like to avoid the setter, since nothing really happens in it. So I'd prefer public or package protected. What do you recommend?

推荐答案

我更喜欢设定者


  • 更容易调试(在设置器中放置断点而不是现场访问/修改)

  • 更容易记录

  • 更容易添加一些验证(虽然这并不总是最好的地方)

  • 更容易支持双向维护(尽管IOC容器可以照顾)

  • 任何其他手动AOP目的

  • it is easier to debug (put a breakpoint in a setter rather than on field access / modification)
  • easier to log
  • easier to add some validation (although this is not always the best place)
  • easier to support bidirectional maintainance (though IOC container can take care of that)
  • any other "manual AOP" purpose

但这只是我的意见

这篇关于注入私人,包裹或公共场地或提供设定者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆