简体   繁体   中英

@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?

@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. 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

Thanks for hints

If you have only one constructor you don't need @Autowired . If you have more than one you have to say to String which exactly constructor should be used. In this case, @Autowired is needed.

@Autowired by default uses field injection. You need not to write that constructor or any setter for it. Just having any of the annotation that you have mentioned will work. So all of these annotation will make the beans of the class. 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.

checkout this post Spring inject without autowire annotation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM