Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring注解@Autowired是如何工作的?_Spring_Dependency Injection_Autowired - Fatal编程技术网

Spring注解@Autowired是如何工作的?

Spring注解@Autowired是如何工作的?,spring,dependency-injection,autowired,Spring,Dependency Injection,Autowired,我遇到了一个@Autowired的例子: public class EmpManager { @Autowired private EmpDao empDao; } @Component (or @Controller, or @Service...) class myClass { // tells the application context to inject an instance of EmpDao here @Autowired EmpDao empDao; p

我遇到了一个
@Autowired
的例子:

public class EmpManager {
   @Autowired
   private EmpDao empDao;
}
@Component (or @Controller, or @Service...)
class myClass {

// tells the application context to inject an instance of EmpDao here
@Autowired
EmpDao empDao;


public void useMyDao()
{
    empDao.method();
}
...
}
我对
empDao
get集很好奇,因为没有setter方法,而且它是私有的。

Spring使用API来提供自动连接的依赖注入


工具书类
进一步阅读
  • 罗德约翰逊

Java允许您通过反射与类的私有成员交互


签出,这对于编写单元测试非常方便。

Java允许通过反射框架的一部分(包括
field
method
继承自
AccessibleObject
)关闭对字段或方法的访问控制(是的,首先要通过安全检查)。一旦这个字段可以被发现并写入,剩下的工作就很简单了;仅仅是一个。

不需要任何setter,您只需使用注释
@component
声明
EmpDao
类,以便Spring将其标识为ApplicationContext中包含的组件的一部分

您有两种解决方案:

  • 要在XML文件applicationContext中手动声明bean,请执行以下操作:
通过
@Autowired
对其引用进行注释:

public class EmpManager {
   @Autowired
   private EmpDao empDao;
}
@Component (or @Controller, or @Service...)
class myClass {

// tells the application context to inject an instance of EmpDao here
@Autowired
EmpDao empDao;


public void useMyDao()
{
    empDao.method();
}
...
}
通过将一个bean的实例放置到另一个bean实例中所需的字段中来实现自动连接。这两个类都应该是bean,也就是说,它们应该被定义为存在于应用程序上下文中


Spring知道bean
EmpDao
MyClass
的存在,并将在
MyClass
中自动实例化
EmpDao
的一个实例,如果您没有猜到的话,我对Spring开发人员编写代码的流畅性印象深刻。我知道他们是如何做到的,但这并不能改变它的优点。我遇到过一些代码,在我添加公共setter方法之前,不会注入自动连线属性。是什么原因造成的?@Snekse:不知道。作为一个完整的问题提问,包括所使用的Spring的确切版本和所讨论的代码,也许-可能-有人会告诉你。这可能是由于Java安全策略设置的,它禁止使用反射访问私有字段。如果我得到了你的答案,只需交叉检查即可。。你的意思是-访问控制是自动关闭的,那么类中的私有访问说明符需要什么呢?如果它是@autowireless,我错了,@autowireless不需要任何检测,只需要反射。像@Transactional这样的其他注释确实需要插装。我同意,@Autowired不应该使用CGLib。只有工厂注入或代理类等,看看这篇文章可能重复的
@Component (or @Controller, or @Service...)
class myClass {

// tells the application context to inject an instance of EmpDao here
@Autowired
EmpDao empDao;


public void useMyDao()
{
    empDao.method();
}
...
}