@Autowired vs @Required on setter [英] @Autowired vs @Required on setter

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

问题描述

我很想知道这样的代码有什么区别:

I'm curious to know what's the difference between code like this:

class MyClass {
   @Autowired
   MyService myService;
}

和这样的代码:

class MyClass {
   MyService myService;

   @Required
   public void setMyService(MyService val) {
       this.myService = val;
   }
}


推荐答案

<当您想要自动装配bean时,使用code> @Autowired 注释。 @Autowired 不限于setter。它也可以与构造函数和字段一起使用。如果您在字段上使用 @Autowired 注释,该字段将使用具有匹配数据类型的bean自动装配。

@Autowired annotation is used when you want to autowire a bean. @Autowired is not limited to setter. It can be used with a constructor and a field as well. If you use @Autowired annotation on a field, that field will be autowired with bean having matching data type.

@Required 检查是否已设置特定属性。如果字段已使用 @Required 注释进行注释,并且未设置该字段,则将获得 org.springframework.beans.factory.BeanInitializationException

@Required checks if a particular property has been set or not. If a field has been annotated with @Required annotation and that field is not set, you will get org.springframework.beans.factory.BeanInitializationException.

参考:

Spring @Autowired usage

Spring的@Required注释的推荐用法

编辑:正如'kryger'指出:用 @Autowired 注释的字段实际上也是 @Required (除非你明确地将其参数设置为false)。
例如:

As pointed by 'kryger': field annotated with @Autowired is effectively also @Required (unless you explicitly set its parameter required to false). eg:

@Autowired(required=false)
private ObjectType objectType;

对于已注释的字段 @Autowired ,如果具有匹配数据类型的bean不可用,则抛出 org.springframework.beans.factory.BeanCreationException

For a field that has been annotated @Autowired, if bean with matching data type in not available, org.springframework.beans.factory.BeanCreationException is thrown.

这篇关于@Autowired vs @Required on setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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