java @autowired 注释如何用于私有字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28694204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:00:48  来源:igfitidea点击:

How does @autowired annotation works for a private field?

javaspring

提问by Vishnudev K

How does @Autowiredannotation work for a private field without a getter and a setter? How can spring access a private field?

@Autowired注释如何在没有 getter 和 setter 的情况下为私有字段工作?spring如何访问私有字段?

回答by wastl

It works with reflection. Hereyou can find an example of how to set public fields. But setting private fields does not make much of a difference

它适用于反射。您可以在此处找到有关如何设置公共字段的示例。但是设置私有字段并没有太大区别

The only difference with a private field is that you will need to set the setAccessible before you are able to read/write to the field. Further, this method can throw a SecurityException. Java Docs

与私有字段的唯一区别是您需要先设置 setAccessible,然后才能读/写该字段。此外,此方法可以抛出 SecurityException。 Java 文档

回答by anurag gupta

@Component
public class A(){}

@Component
public class B(){
@Autowired
private A a;
}

Spring create beans mentioned as @Component. here bean A will be created first and since B is dependent on A, then injection of A to B is done. there's no need for any setters. just @Component is required. Spring uses CGLib for creation of beans using reflection.

Spring 创建以@Component 命名的 bean。这里首先创建 bean A 并且由于 B 依赖于 A,然后将 A 注入到 B 完成。不需要任何二传手。只需要@Component。Spring 使用 CGLib 通过反射创建 bean。

回答by Rajesh

Three types of dependency injection

依赖注入的三种类型

There are at least three ways an object can receive a reference to an external module:

对象至少可以通过三种方式接收对外部模块的引用:

constructor injection:the dependencies are provided through a class constructor.

构造函数注入:依赖项通过类构造函数提供。

setter injection:the client exposes a setter method that the injector uses to inject the dependency.

setter 注入:客户端公开一个 setter 方法,注入器使用该方法注入依赖项。

interface injection:the dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency.

接口注入:依赖提供了一个注入器方法,该方法将依赖注入任何传递给它的客户端。客户端必须实现一个接口,该接口公开接受依赖项的 setter 方法。