先看代码:
@RestController @RequestMapping("/test") public class TestController { private final TestService testService; // @Autowired public TestController(TestService testService) { this.testService = testService; } @RequestMapping("/sayHello") public String sayHello() { return testService.sayHello(); } }
@Autowired并不是必须的,不加也能注入成功,这是为什么?
在 Spring4.x 中增加了新的特性:如果类只提供了一个带参数的构造方法,则不需要对对其内部的属性写 @Autowired 注解,Spring 会自动为你注入属性。
前言
因为业务关系也看了些同事写的代码,因为公司没有明确规定,有一部分人在注入依赖的时候使用了用Spring推荐的构造器注入的方式,一部分人使用了@Autowired的注解进行注入。
因此,接下来我试着总结归纳一下相关的情况,做一次回顾。
用自己的话去说出来才算是真的掌握。
使用介绍
1.@Autowired注入
@RestController @RequestMapping("/test") public class TestController { @Autowired priv