2016-06-09 74 views
0

我碰到这个代码我们为什么在这里标注类@Autowire

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

我看到@Autowire上的字段, 这意味着按类型自动装配,与类别这一领域将获得与特定类型的豆。

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

这是Spring-Jersey Rest项目。

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

我的问题是,

1)这是谁的班?

2)在这里按名称自动装配完成后,我可以用@Resource替换@Autowired吗?

回答

0

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

这与使用XML配置的bean元素的autowire属性类似。假设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来实现同样的目的。但是在这种情况下,您必须注释字段或设置者。并且还如果依赖未在容器发现注射将失败

@Singleton @Controller @Autowire(模式= AutowireMode.BY_NAME) @Path( “/”) 公共类RootResource {

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

相关问题