Spring注解@Autowired如何工作?
我遇到了一个 @Autowired 的例子:
public class EmpManager {
@Autowired
private EmpDao empDao;
}
我很好奇 empDao 如何获取集合,因为没有 setter 方法而且它是私有的。
I came across an example of @Autowired
:
public class EmpManager {
@Autowired
private EmpDao empDao;
}
I was curious about how the empDao
get sets since there are no setter methods and it is private.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 允许通过
AccessibleObject.setAccessible()
方法,它是反射框架的一部分(都是Field
和Method
继承自AccessibleObject
)。一旦可以发现并写入该字段,剩下的事情就变得非常简单;只是一个简单的编程问题。Java allows access controls on a field or method to be turned off (yes, there's a security check to pass first) via the
AccessibleObject.setAccessible()
method which is part of the reflection framework (bothField
andMethod
inherit fromAccessibleObject
). Once the field can be discovered and written to, it's pretty trivial to do the rest of it; merely a Simple Matter Of Programming.Java 允许您通过反射与类的私有成员进行交互。
查看 ReflectionTestUtils ,这对于编写单元测试非常方便。
Java allows you to interact with private members of a class via reflection.
Check out ReflectionTestUtils, which is very handy for writing unit tests.
不需要任何设置器,您只需使用注释
@component
声明EmpDao
类,以便 Spring 将其识别为 ApplicationContext 中包含的组件的一部分...您有 2 个解决方案:
AND 使用 spring 注释来声明以下类:你的 spring 容器将作为组件进行管理:
AND 通过
@Autowired
注释其引用:通过将一个 bean 的实例放入另一个 bean 实例中的所需字段来进行自动装配。这两个类都应该是 bean,即它们应该被定义为存在于应用程序上下文中。
Spring 知道 bean
EmpDao
和MyClass
的存在,并将在MyClass
中自动实例化EmpDao
的实例。No need for any setter, you just have to declare the
EmpDao
class with the annotation@component
in order that Spring identifies it as part of the components which are contained in the ApplicationContext ...You have 2 solutions:
AND to use the spring annotation to declare the classes that your spring container will manage as components:
AND to annotate its reference by
@Autowired
:Autowiring happens by placing an instance of one bean into the desired field in an instance of another bean. Both classes should be beans, i.e. they should be defined to live in the application context.
Spring knows the existence of the beans
EmpDao
andMyClass
and will instantiate automatically an instance ofEmpDao
inMyClass
.Spring 使用 CGLib API 提供自动装配依赖注入。
参考文献
进一步阅读
Spring uses the CGLib API to provide autowired dependency injection.
References
Further Reading