【发布时间】:2020-10-28 03:50:55
【问题描述】:
我正在为在家中进行一些有趣的学习/教程设置一个新的 Spring 项目,我似乎遇到了一个相当普遍的问题,但我已经尝试了我在这里找到的所有可能的解决方案,但没有运气。基本上我所拥有的如下:
控制器类:
@RestController
@RequestMapping(value = "/shop")
public class ShopController {
@Autowired
ShopService shopService;
@GetMapping(value = "/{id}")
public @ResponseBody Shop getTestData(@PathVariable String id) {
return shopService.getShopBasedOnId(id);
}
}
服务类:
@Service
public class ShopService {
@Autowired
private ShopRepository shopRepository;
public ShopService(ShopRepository shopRepository){
this.shopRepository = shopRepository;
}
public Shop getShopBasedOnId(String id) {
return shopRepository.findByShopId(id);
}
}
存储库类:
@Repository
public interface ShopRepository extends PagingAndSortingRepository<Shop, String> {
Shop findByShopId(String shopId);
}
应用类:
@SpringBootApplication
@EnableJpaRepositories("com.example.reservations.repository")
public class ReservationsApplication {
public static void main(String[] args) {
SpringApplication.run(ReservationsApplication.class, args);
}
}
最后但并非最不重要的是我的 pom.xml 与依赖项:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-couchbase</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
所以我得到的错误代码如下:
Description:
Parameter 0 of constructor in com.example.reservations.services.ShopService required a bean of type 'com.example.reservations.repository.ShopRepository' 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 'com.example.reservations.repository.ShopRepository' in your configuration.
我的文件夹结构是:
main
|_java
|_com.example.reservations
|_controllers
|_ShopController.java
|_repository
|_ShopRepository.java
|_services
|_ShopService.java
|_ReservationsApplication.java
【问题讨论】:
-
您是否尝试使用
@Component注释ShopService以便 Spring 在进行组件扫描时可以找到它? -
我在 ShopService 上有
@Service注释,是不是像 @Component 一样包含在其中? -
我看到你更新了源代码。是的,
@Service应该足够了。 -
Shop实体主键的数据类型是什么,是String
-
删除 ShopService 中字段上的 @Autowired ,您正在使用字段注入和构造函数注入。
标签: java spring dependencies repository javabeans