@Autowired vs @Required on setter

0x5*_*94E 28 java resources spring autowired required

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

class MyClass {
   @Autowired
   MyService myService;
}
Run Code Online (Sandbox Code Playgroud)

和这样的代码:

class MyClass {
   MyService myService;

   @Required
   public void setMyService(MyService val) {
       this.myService = val;
   }
}
Run Code Online (Sandbox Code Playgroud)

Sud*_*SMD 39

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

@Required检查是否已设置特定属性.如果一个字段已注释@Required注释并且该字段未设置,您将获得org.springframework.beans.factory.BeanInitializationException.

参考:

Spring @Autowired用法

Spring的@Required注释的推荐用法

编辑:正如'kryger'指出的那样:带注释的字段@Autowired也是有效的@Required(除非你明确地将其参数设置为false).例如:

@Autowired(required=false)
private ObjectType objectType;
Run Code Online (Sandbox Code Playgroud)

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

  • 值得添加的是,使用`@Autowired`注释的字段实际上也是`@ Required`(除非你明确地将其参数`required`设置为false) (8认同)
  • @ user2171669 - 按配置时间,如果你的意思是启动时间,那么是,@ Required需要在启动时完成.创建Bean时将检查@Request,即初始化Spring上下文时.如果你的意思是编译时间,那么没有.这一切都发生在上下文初始化时.请注意,在配置中指定<context:component-scan />会告诉Spring检查@ Required注释.另请检查RequiredAnnotationBeanPostProcessorhttps://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.html (2认同)

wat*_*hme 8

@Autowired是不一样的@Required.

@Autowire-Annotation告诉Spring,这家酒店是在一个XML的文件,然后导致财产被在XML的文件中给出的信息注入.因此,将它作为一个整体来看,这个注释专门用于告诉Spring该属性必须由XML-configuration-File中给出的信息注入,而不是通过注释.使用@Required-Annotation 时无关紧要.

@Autowired-Annotation(在你的代码示例),讲述的ApplicationContext(又名春-IOC-Containter)注入所需的依赖.(无论如何,如果它通过使用注释或ApplicationContext的XML文件).

@Required-Annotation,讲述的ApplicationContext,这个属性在XML文件(ApplicationContext中的XML的文件)被提及,但对自己的注解并没有告诉注入的依赖.因此,它用于检查它是否在XML配置文件中,而不是注入依赖项.注入完成是因为XML文件中提到了该属性.

所以最后它告诉我必须完成注入,因为XML-File中的配置.但同样:注释并没有说明必须注入依赖项,而是必须在XML-File中提及它 - 然后才能注入依赖项.

在XML文件中提到属性我的意思是这样的配置:

<bean id="MyClass" class="com.myclasses.common.MyClass">
     <property name="someProperty" value="ValueThatHasToBeInjected" />
</bean>
Run Code Online (Sandbox Code Playgroud)

那么我为什么要在@Autowired-Annotation上使用它呢?

当必须通过XML配置文件中的信息注入依赖项时,应该使用它.

能给我举个例子?

嗯,这个网站已经有一个非常好的例子.这也是解释的地方.