[英]Are getters and setters needed for CDI injected beans?
When a bean is injected using CDI:当使用 CDI 注入 bean 时:
@Inject Person person;
Is a setter and getter needed/recommended?是否需要/推荐使用 setter 和 getter?
import javax.inject.Inject;
import javax.inject.Named;
@Named
@SessionScoped
public class myJSFBean{
@Inject Person person;
public void setPerson (Person person){
this.person = person;
}
public Person getPerson (){
return person;
}
I have found this documentation, but I don't understand what it means: http://docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html我找到了这个文档,但我不明白它的意思: http : //docs.oracle.com/javaee/6/tutorial/doc/gjbbp.html
According to Weld Documentation :根据焊接文件:
Notice that it isn't necessary to create a getter or setter method to inject one bean into another.
请注意,没有必要创建 getter 或 setter 方法来将一个 bean 注入另一个 bean。 CDI can access an injected field directly (even if it's private!), which sometimes helps eliminate some wasteful code.
CDI 可以直接访问注入的字段(即使它是私有的!),这有时有助于消除一些浪费的代码。 The name of the field is arbitrary.
字段的名称是任意的。 It's the field's type that determines what is injected.
字段的类型决定了注入的内容。
CDI ( Container Dependency Injection ) within Java EE 6 application can target different injection points: fields, constructors and setters . Java EE 6 应用程序中的CDI (容器依赖注入)可以针对不同的注入点:字段、构造函数和设置器。
So the short answer is no , you do not need a setter method if you won't be using it as the injection point.所以简短的回答是否定的,如果您不将其用作注入点,则不需要setter方法。
The getter can be ignored as well unless you need one to access the field state (which by experience does not make much sence in a CDI environment, the same field that has been injected by the container still can be accessed through it in other components).除非您需要访问字段状态,否则也可以忽略getter (根据经验,这在CDI环境中没有多大意义,容器注入的相同字段仍然可以在其他组件中通过它访问) .
I would even consider a getter harmful.我什至会认为吸气剂有害。
Due to the encapsulation principle, getters and setters are public by default in most IDEs and in your example above, too.由于封装原则,在大多数 IDE 和上面的示例中,默认情况下 getter 和 setter 是公开的。 This means you pollute your autocomplete with CDI injects.
这意味着您会使用 CDI 注入污染您的自动完成功能。 These shouldn't be visible outside of your class.
这些不应该在您的课堂之外可见。
If you access an @ApplicationScoped
been via a getter in a @RequestScoped
bean, the request scoped bean will always be instantiated needlessly, which costs performance.如果您通过
@RequestScoped
bean 中的 getter 访问@ApplicationScoped
,则请求范围的 bean 将始终被不必要地实例化,这会降低性能。 CDI beans should always be injected where they are needed and not being accessed across beans. CDI bean 应该总是被注入到需要它们的地方,而不是被跨 bean 访问。 You will prevent CDI from handling your scopes correctly.
您将阻止 CDI 正确处理您的范围。
So all there is really left is a private getter, which is superfluous anyway, because you will never have to modify a cdi bean before you return it.所以真正剩下的只是一个私有的getter,这无论如何都是多余的,因为在返回之前你永远不必修改 cdi bean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.