@Autowired vs @Required on setter
我很想知道这样的代码有什么区别:
class MyClass { @Autowired MyService myService; }
和这样的代码:
class MyClass { MyService myService; @Required public void setMyService(MyService val) { this.myService = val; } }
当您想要自动assemblybean时,使用@Autowired
注释。 @Autowired
不仅限于二传手。 它也可以与构造函数和字段一起使用。 如果在字段上使用@Autowired
批注,则该字段将使用具有匹配数据类型的bean自动assembly。
@Required
检查是否已设置特定属性。 如果某个字段已使用@Required
注释进行注释且该字段未设置,则会获得org.springframework.beans.factory.BeanInitializationException
。
参考:
Spring @Autowired用法
Spring的@Required注释的推荐用法
编辑:正如’kryger’指出:使用@Autowired
注释的字段实际上也是@Required
(除非您明确将其参数设置为false)。 例如:
@Autowired(required=false) private ObjectType objectType;
对于已注释@Autowired
的字段,如果具有匹配数据类型的bean不可用,则抛出org.springframework.beans.factory.BeanCreationException
。
@Autowired
与@Required
。
@Required
-Annotation专门用于告诉Spring必须通过XML-configuration-File中给出的信息注入此属性,而不是通过注释。 使用@Autowire
-Annotation时无关紧要。
@Autowire
-Annotation (在代码示例中)告诉ApplicationContext(也称为Spring-IoC-Containter)注入所需的依赖项。 (无论如何,如果它通过使用注释或ApplicationContext的XML文件)。
@Required
-Annotation告诉ApplicationContext必须在XML文件(ApplicationContext的XML-File)中提及此属性,但Annotation本身并不告诉注入依赖项。 因此,它用于检查它是否在XML配置文件中,而不是注入依赖项。 注入完成是因为XML文件中提到了该属性。
所以最后它告诉我必须完成注入,因为XML-File中的配置。 但同样:注释并没有说明必须注入依赖项,而是必须在XML-File中提及它 – 然后才能注入依赖项。
在XML文件中提及属性我的意思是这样的配置:
那么我为什么要在@Autowired-Annotation上使用它呢?
当必须通过XML配置文件中的信息注入依赖项时,应该使用它。
你可以给我一个例子吗?
嗯, 这个网站已经有一个非常好的例子了。 这也是解释的地方。
- 使用Spring-WS客户端动态设置自定义HTTP标头
- Spring:将某种类型的数组或列表注入bean中
- 如何将AD组映射到用户角色Spring Security LDAP
- 在Spring MVC中,从哪里开始和结束计数器来测试速度执行时间?
- Eclipse:添加javadoc
- 如何匹配包含“/”的@pathVariable的Spring @RequestMapping?
- 在Spring Servlet项目的web.xml中加载contextConfigLocation的顺序
- DefaultAnnotationHandlerMapping通过ContextLoaderListener而不是Spring 3上的DispatcherServlet
- Spring MVC中重定向和视图呈现的区别