当我尝试自动装配组件时,出现NoSuchBeanDefinitionException
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.github.robertobatts.restapi.repository.OrderRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
这是我尝试自动连线的代码:
@CrossOrigin(origins = "*")
@RestController
@RequestMapping(value = "/order", produces = "application/json")
public class OrderController {
@Autowired
private OrderRepository repository;
...
}
这是组件:
@Component
public class OrderRepository extends InMemoryRepository<Order> {
@Override
protected void updateIfExists(Order original, Order updated) {
original.setDescription(updated.getDescription());
original.setCostInCents(updated.getCostInCents());
original.setComplete(updated.isComplete());
}
}
OrderRepository使用的所有对象都是没有弹簧注释的标准Java对象。
这是软件包的结构:
restapi
SpringBootApplication.java
controller
OrderController.java
repository
OrderRepository.java
答案 0 :(得分:1)
请将您的@SpringBootApplication
annotated class升级一个包。
注释本身包含@ComponentScan
和...
如果未定义特定的程序包,则将从声明此注释的类的程序包中进行扫描。
34ced93
上的这些更改使我使用mvn clean spring-boot:run
获得了预期的标准行。
diff --git a/src/main/java/com/github/robertobatts/restapi/main/RestApiExampleApplication.java b/src/main/java/com/github/robertobatts/restapi/RestApiExampleApplication.java
similarity index 86%
rename from src/main/java/com/github/robertobatts/restapi/main/RestApiExampleApplication.java
rename to src/main/java/com/github/robertobatts/restapi/RestApiExampleApplication.java
index bc01db5..affb928 100644
--- a/src/main/java/com/github/robertobatts/restapi/main/RestApiExampleApplication.java
+++ b/src/main/java/com/github/robertobatts/restapi/RestApiExampleApplication.java
@@ -1,3 +1,3 @@
-package com.github.robertobatts.restapi.main;
+package com.github.robertobatts.restapi;
import org.springframework.boot.SpringApplication;
diff --git a/src/main/java/com/github/robertobatts/restapi/repository/OrderRepository.java b/src/main/java/com/github/robertobatts/restapi/repository/OrderRepository.java
index b356e74..554610a 100644
--- a/src/main/java/com/github/robertobatts/restapi/repository/OrderRepository.java
+++ b/src/main/java/com/github/robertobatts/restapi/repository/OrderRepository.java
@@ -1,4 +1,6 @@
package com.github.robertobatts.restapi.repository;
+import javax.annotation.PostConstruct;
+
import org.springframework.stereotype.Repository;
@@ -8,4 +10,9 @@ import com.github.robertobatts.restapi.domain.Order;
public class OrderRepository extends InMemoryRepository<Order> {
+ @PostConstruct
+ private void test() {
+ System.out.println("OrderRepository ready.");
+ }
+
@Override
protected void updateIfExists(Order original, Order updated) {