gpt4 book ai didi

spring - Autowire 不适用于 Controller Spring Boot

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

每当我尝试 Autowiring 在我​​的 Controller 类中实现 JPA 存储库的自定义存储库时,它都无法执行此操作并抛出 no bean def find 错误,而如果我对任何服务类执行相同的操作,则它工作正常。谁能给我解释一下为什么会这样吗?


Spring Boot
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-02-15 13:01:50.169 ERROR 16304 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :

***************************
APPLICATION FAILED TO START
***************************

Description:

Field customerRepo in Controllers.MainController required a bean of type 'Repository.CustomerRepo' that could not be found.

The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'Repository.CustomerRepo' in your configuration.

```
@SpringBootApplication
@ComponentScan(basePackages = "Controllers")
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}
``````````````````
@RestController
@RequestMapping("/")
public class MainController {

@Autowired
private CustomerRepo customerRepo;

@RequestMapping(value = "/home", method = RequestMethod.GET)
public String homePage() {
Customer testCustomer = new Customer();
testCustomer.setFirstName("csdcsdccs");
testCustomer.setLastName("csdcsdccs");
testCustomer.setMiddleName("csdcsdccs");
testCustomer.setAddressLine("csdcsdccs");
testCustomer.setCountry("csdcsdccs");
testCustomer.setPincode(713201);
testCustomer.setState("csdcsdccs");
testCustomer.setDateOfBirth(new Date(2019, 5, 13));

customerRepo.save(testCustomer);

return "inserted";
}
}

`````````````
@Repository
public interface CustomerRepo extends CrudRepository<Customer, Long> {

}
``````````````````````````


最佳答案

Spring 应用程序无法扫描存储库。您能否检查一下存储库是否已在基础包下定义,否则也在 @ComponentScan 中添加存储库存储库包。

@SpringBootApplication
@ComponentScan(basePackages = {"Controllers","Repository"})
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

}

关于spring - Autowire 不适用于 Controller Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236759/

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