【问题标题】:@Autowired on classes in Spring@Autowired 在 Spring 中的类上
【发布时间】:2020-05-22 13:00:47
【问题描述】:

我有一个小问题。如果该类使用 @Component、@Service、@Controller 或 @Repository 进行注释,并且我想注入其依赖项,是否需要 @Autowired?

@RestController
@RequestMapping(value = "/goods", produces = APPLICATION_JSON_VALUE)
@SuppressWarnings("squid:S4684")
public class UserDeviceRestController implements UserDeviceRestApi {

  private final UserDeviceService userDeviceService;

  public UserDeviceRestController(UserDeviceService userDeviceService) {
    this.userDeviceService = userDeviceService;
  }

这段代码非常适合我,因为它是在 UserDeviceService 中指定的 @Service 注释。是因为这个吗?

如果我有一个没有这些注释之一的类(粗体),我假设我必须在构造函数/字段/设置器中 @Autowired 它然后......那么为什么不在所有可能的依赖注入类之上指定 @Component并且不记得@Autowired

感谢提示

【问题讨论】:

  • 我会将 Autowired 注释添加到构造函数中,并将 Qualifier 注释添加到每个参数中,以说明需要哪个 bean。
  • 在较新版本的 Spring 中,在这种情况下不需要 @Autowired 注释。 Spring 足够聪明,可以从你的类 UserDeviceRestController 的构造函数中理解它应该寻找一个 UserDeviceService bean 来传递它。
  • Spring 将所有 @Component 注释类视为 bean,并使其准备好注入。对于那些很少用作依赖项的字段,我会使用@Autowired
  • 对于组件而言...RestController 是一个组件...因为RestController 继承自Controller 而Controller 是一个组件。对于自动接线,请参见此处stackoverflow.com/questions/41092751/…
  • @michalk 从 Spring 4.3 开始更准确地说:docs.spring.io/spring/docs/4.3.x/spring-framework-reference/…

标签: java spring spring-boot


【解决方案1】:

如果您只有 一个 构造函数,则不需要@Autowired。如果你有多个,你必须告诉 String 应该使用哪个构造函数。在这种情况下,需要@Autowired

【讨论】:

    【解决方案2】:

    @Autowired 默认使用字段注入。您不需要为它编写该构造​​函数或任何设置器。只需拥有您提到的任何注释即可。所以所有这些注解都会成为类的bean。以下是这些注释的详细信息。

     @Component is a generic stereotype for any Spring-managed component or bean. 
        @Repository is a stereotype for the persistence layer.
        @Service is a stereotype for the service layer.
        @Controller is a stereotype for the presentation layer (spring-MVC).
    

    从 Spring 4.3 开始,构造函数注入不需要注解。

    查看此帖子Spring inject without autowire annotation

    【讨论】:

      猜你喜欢
      • 2019-02-20
      • 2012-04-10
      • 1970-01-01
      • 2012-03-30
      • 1970-01-01
      • 2018-10-04
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多