spring构造注入不需要加@Autowired?

@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并不是必须的,不加也能注入成功,这是为什么?

阅读 10.4k
3 个回答

在 Spring4.x 中增加了新的特性:如果类只提供了一个带参数的构造方法,则不需要对对其内部的属性写 @Autowired 注解,Spring 会自动为你注入属性。

4.3 之后的功能,如果只有一个构造方法,自动用这个构造方法注入
配合lombok的 @RequiredArgsConstructor 使用体验很好

因为你加了@RestController,那么这个类就交由spring管理了,这里不用@Autowired的原因是,spring会对管理的bean的非默认构造函数的入参,尽量匹配的实例,进行实例化,这就是spring的构造函数注入

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题