Java中@Autowired注解的好处 [英] benefit of @Autowired annotation in Java

查看:24
本文介绍了Java中@Autowired注解的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许是因为我的英文错误,我无法理解使用@Autowired注解的好处.

Maybe, because of my wrong English, I couldn't understand the benefit of using @Autowired annotation.

根据教程,我们可以通过@Autowired 将第一种(I.)情况简化为第二种情况(II.).

According to the tutorial we can simplify the first(I.) case to second case(II.) by means of @Autowired.

我的问题是,@Autowired 的含义是什么?因为它没有告诉更多,因为没有使用@Autowired,编译器可以根据声明找出EmpDao emDao"和EmpManager"密切相关.

代码引用自 这里

我.

    <bean id="empDao" class="EmpDao" />
    <bean id="empManager" class="EmpManager">
       <property name="empDao" ref="empDao" />
    </bean>

public class EmpManager {

   private EmpDao empDao;

   public EmpDao getEmpDao() {
      return empDao;
   }

   public void setEmpDao(EmpDao empDao) {
      this.empDao = empDao;
   }

   ...
}

二.

<context:annotation-config />

<bean id="empManager" class="autowiredexample.EmpManager" />
<bean id="empDao"     class="autowiredexample.EmpDao" />

import org.springframework.beans.factory.annotation.Autowired;

public class EmpManager {

   @Autowired
   private EmpDao empDao;

}

推荐答案

@Autowired 是 spring 特定的.@Inject 是标准的等价物.它是一个注解,告诉上下文(spring,或者在 @Inject 的情况下 - 任何 DI 框架)尝试将对象设置到该字段中.

@Autowired is spring-specific. @Inject is the standard equivallent. It is an annotation that tells the context (spring, or in the case of @Inject - any DI framework) to try to set an object into that field.

编译器与此无关 - DI 框架(spring)在运行时实例化您的对象,然后在您指定的点设置它们的依赖项 - 通过 XML 或通过注释.

The compiler has nothing to do with this - it is the DI framework (spring) that instantiates your objects at runtime, and then sets their dependencies at the points you have specified - either via XML or via an annotation.

我同意 DI 框架可能会尝试将依赖项注入所有字段,即使它们没有被注释.(如果要排除特定字段,请对其进行注释).但他们选择了另一种策略(configuration-over-convention).顺便说一句:

I agree it is a possible scenario for a DI framework to try to inject dependencies into all fields, even if they are not annotated. (And if you want to exclude a particular field, to annotate it). But they chose the other strategy (configuration-over-convention). By the way:

  • 如果使用 xml config 并选择某种形式的自动装配,bean 的依赖项将自动装配,无需指定任何内容
  • 您可以指定每个上下文的自动装配设置.

这篇关于Java中@Autowired注解的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆