[英]@Autowired on classes in Spring
我有一个小问题。 如果该类使用@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 注释。 是因为那个吗?
如果我有一个没有这个注释(粗体)的类,我假设我必须在构造函数/字段/setter中@Autowired然后......那么为什么不在所有可能的依赖注入类之上指定@Component而不是记得@Autowired
谢谢提示
如果您只有一个构造函数,则不需要@Autowired
。 如果你有多个,你必须告诉 String 应该使用哪个构造函数。 在这种情况下,需要@Autowired
。
@Autowired 默认使用字段注入。 您不需要为它编写该构造函数或任何 setter。 只需使用您提到的任何注释即可。 因此,所有这些注释都将成为类的 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 注入没有自动装配注释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.