为什么在这里我们用@Autowire注解class

Why here we annotate class with @Autowire

我看到这段代码

   @Singleton
    @Controller
    @Autowire(mode = AutowireMode.BY_NAME)
    @Path("/")
    public class RootResource {
    }

我在字段上看到了@Autowire, 这意味着按类型自动装配,并且 class 使用此字段将获得特定类型的 bean。

但是在上面的代码中我不确定谁在使用这个 RootResource bean?

这是 Spring-球衣休息项目。

我的理解是 spring 将创建 RootResource 的 bean,并且 Some class 将使用该 bean 来设置它的 属性。 (我看不到这个 bean 的任何显式配置)

我的问题是,

1) 这个class是谁?

2) 至此按名称自动装配完成,我可以将@Autowired 替换为@Resource 吗?

在这种情况下使用@Autowire 是指示Spring 容器通过使用名称与RootResource 中属性 名称匹配的bean 将依赖项注入RootResource。

这类似于使用 XML 配置的 bean 元素的自动装配属性。假设 RootResource 有

@Singleton
@Controller
@Autowire(mode = AutowireMode.BY_NAME)
@Path("/")
public class RootResource{

   private SomeService someService;

   private AnotherService anotherService;

   public void setSomeService(SomeService someService){
      this.someService = someService;
   }

   public void setAnotherService(AnotherService anotherService){
      this.anotherService = anotherService;
   }

 }

容器将尝试查找名为 someService 和 anotherService 的 bean,并尝试设置相应的属性。请注意,您不需要 属性 或字段级别的任何依赖项注入注释。

您可以使用@Resource / @Autowired 来实现相同的目的。但是,在这种情况下,您必须注释字段或设置器。如果在容器中找不到依赖项,注入也会失败

@单例 @控制器 @Autowire(模式=AutowireMode.BY_NAME) @小路(”/”) public class 根资源{

   private SomeService someService;

   private AnotherService anotherService;

   @Resource
   public void setSomeService(SomeService someService){
      this.someService = someService;
   }

   @Resource
   public void setAnotherService(AnotherService anotherService){
      this.anotherService = anotherService;
   }

 }

@Resource 将使用 bean 名称并回退到类型匹配,而 @Autowired 始终使用类型匹配

另请注意@Autowire 和@Autowired 具有不同的行为。 RootResource bean 不需要在应用程序上下文中显式配置。它会被组件扫描器自动检测到,因为它有一个构造型注释,即@Controoler