简体   繁体   English

Spring getter 和 setter 依赖?

[英]Spring getter and setter dependent?

I would like to make sure if I understand this correctly.我想确定我是否正确理解了这一点。 Spring needs a setter to inject a field reference? Spring 需要一个 setter 来注入字段引用吗? Couldn't it do it by just detecting it as a public field?它不能通过将其检测为公共领域来做到这一点吗?

Is there an alternative to this.有没有替代方法。 From what I understand Java EE's @Inject annotation can do this without any problem.据我了解,Java EE 的 @Inject 注释可以毫无问题地做到这一点。 But I have always been inclined more to Spring.但我一直更倾向于春天。

This depends on how you're creating your bean.这取决于您如何创建 bean。 Spring does not require setters. Spring 不需要 setter。 There are a number of other ways:还有许多其他方式:

  • Autowiring (with or without Qualifiers) via annotation at the field level通过字段级别的注释自动装配(带或不带限定符)
  • Constructor injection (either by xml or annotations in the code)构造函数注入(通过xml或代码中的注解)

Public fields (as you suggested) might work, though i have never tried it, and would advise against it even if it does.公共领域(如您所建议的)可能会起作用,尽管我从未尝试过,并且即使确实如此,也会建议不要这样做。

Unfortunately, the XML approach does not look into private fields (that i know of).不幸的是,XML 方法没有研究私有字段(我知道)。 You either need to add a setter, use the constructor, or set up some sort of autowiring.您要么需要添加一个 setter,使用构造函数,要么设置某种自动装配。

Keep in mind, autowiring can be combined with XML.请记住,自动装配可以与 XML 结合使用。 Spring will pay attention to your wiring annotations even if you create your bean via xml (as opposed to something like @Component and component scanning).即使您通过 xml 创建 bean(而不是像 @Component 和组件扫描之类的东西),Spring 也会注意您的布线注释。

It is not necessary to have Setter to inject a reference, you can use Autowire on a public variable of a class or on the setter method, u can also inject beans using constructor-arg which is a good way of injecting dependencies and autowiring can be done on Constructors also.没有必要让 Setter 注入引用,您可以在类的公共变量或 setter 方法上使用 Autowire,您也可以使用 constructor-arg 注入 bean,这是注入依赖项和自动装配的好方法也在构造函数上完成。 @inject also does the same functionality as @autowired, however @Autowired has an additional behaviour where it internally also uses @required attribute, to see if the bean has a references and injected properly. @inject 也具有与 @autowired 相同的功能,但是 @Autowired 有一个额外的行为,它在内部也使用 @required 属性,以查看 bean 是否具有引用并正确注入。

Spring provides several alternatives for DI besides setter injection.除了 setter 注入之外,Spring 还为 DI 提供了多种替代方案。 For example, you can use constructor injection .例如,您可以使用构造函数注入 Alternatively, you can use Spring's @Autowired annotation for constructor, field or setter injection.或者,您可以将 Spring 的@Autowired注释用于构造函数、字段或 setter 注入。 Since you mentioned it, I guess that you would also be interested in knowing that Spring supports the @Inject annotation.既然你提到了它,我想你也会有兴趣知道 Spring 支持@Inject注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM