【发布时间】: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的构造函数中理解它应该寻找一个UserDeviceServicebean 来传递它。 -
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