Java @春季课程自动连线
我有一个小问题。如果用@Component、@Service、@Controller或@Repository注释该类,并且我希望注入其依赖项,那么我是否需要@AutowiredJava @春季课程自动连线,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个小问题。如果用@Component、@Service、@Controller或@Repository注释该类,并且我希望注入其依赖项,那么我是否需要@Autowired @RestController @RequestMapping(value = "/goods", produces = APPLICATION_JSON_VALUE) @SuppressWarnings("squid:S4684") public class UserDeviceRestController imple
@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注释。是因为这个吗
如果我想要一个没有任何注释(粗体)的类,我假设我必须在constructor/field/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).
从Spring4.3开始,构造函数注入不需要注释
签出这篇文章我会将自动连线注释添加到构造函数中,并将限定符注释添加到每个参数中,以说明需要哪个bean。在较新版本的Spring中,这种情况下不需要
@Autowired
注释。Spring足够聪明,可以从类的构造函数UserDeviceRestController
中理解它应该寻找UserDeviceService
bean来传递它。Spring将所有@Component
注释类视为bean,并使它们准备好注入。对于那些很少用作依赖项的字段,我会使用@Autowired
。。。因为RestController继承自Controller,而Controller是一个组件。关于autowired,请参见此处@michalk(自Spring 4.3起),更准确地说: