gpt4 book ai didi

java - Spring : how this field in controller is injected?

转载 作者:行者123 更新时间:2023-12-02 08:47:47 24 4
gpt4 key购买 nike

我有一个像这样的休息 Controller :

@Slf4j
@RestController
@RequestMapping(...)
public class MyController {

private MyService service;

public MyController(MyService service){
this.service = service;
}

服务类是一个组件:

@Component
public class MyService{
...
}

当我运行程序时,service 字段被正确注入(inject)。但它是如何注入(inject)的(构造函数中的归档ni上都没有 Autowiring 注释)?

我使用的是SpringBoot 2.0。

最佳答案

从 Spring 4.3 版本开始。根据文档( https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-spring-beans-and-dependency-injection ),如果 bean 有单个构造函数,则可以省略 @Autowired 注解。

If a bean has one constructor, you can omit the @Autowired, as shown in the following example:

@Service
public class DatabaseAccountService implements AccountService {

private final RiskAssessor riskAssessor;

public DatabaseAccountService(RiskAssessor riskAssessor) {
this.riskAssessor = riskAssessor;
}

// ...

}

关于java - Spring : how this field in controller is injected?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60974948/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com