spring构造注入不需要加@Autowired?
@RestController
@RequestMapping("/test")
public class TestController {
// @Autowired
private final TestService testService;
public TestController(TestService testService) {
this.testService = testService;
}
@RequestMapping("/sayHello")
public String sayHello() {
return testService.sayHello();
}
}
@Autowired并不是必须的,不加也能注入成功,这是为什么?
在 Spring4.x 中增加了新的特性:如果类只提供了一个带参数的构造方法,则不需要对对其内部的属性写 @Autowired 注解,Spring 会自动为你注入属性。
添加如下注解:
@RequiredArgsConstructor
@RequiredArgsConstructor
public class OperateLogFrameworkServiceImpl implements OperateLogFrameworkService {
private final OperateLogApi operateLogApi;
会自动注入 operateLogApi bean;