[英]@Autowired on classes in Spring
I have a small question.我有一个小问题。 If the class is annotated with @Component, @Service, @Controller or @Repository and I want to inject its dependency, do I need @Autowired?如果该类使用@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;
}
This code works perfect for me because it is @Service annotation specified in UserDeviceService.这段代码非常适合我,因为它是 UserDeviceService 中指定的 @Service 注释。 Is it because of that?是因为那个吗?
If I would have a class without one of this annotations (bolded), I assume I have to @Autowired it in constructor/field/setter then... So why not to specify @Component above all the possible dependency injected classes and do not remember about @Autowired如果我有一个没有这个注释(粗体)的类,我假设我必须在构造函数/字段/setter中@Autowired然后......那么为什么不在所有可能的依赖注入类之上指定@Component而不是记得@Autowired
Thanks for hints谢谢提示
If you have only one constructor you don't need @Autowired
.如果您只有一个构造函数,则不需要@Autowired
。 If you have more than one you have to say to String which exactly constructor should be used.如果你有多个,你必须告诉 String 应该使用哪个构造函数。 In this case, @Autowired
is needed.在这种情况下,需要@Autowired
。
@Autowired by default uses field injection. @Autowired 默认使用字段注入。 You need not to write that constructor or any setter for it.您不需要为它编写该构造函数或任何 setter。 Just having any of the annotation that you have mentioned will work.只需使用您提到的任何注释即可。 So all of these annotation will make the beans of the class.因此,所有这些注释都将成为类的 bean。 Here are the details what these annotation do.以下是这些注释的详细信息。
@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).
From Spring 4.3 annotations are not required for constructor injection.从 Spring 4.3 开始,构造函数注入不需要注解。
checkout this post Spring inject without autowire annotation结帐这篇文章Spring 注入没有自动装配注释
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.