我正在关注Spring Boot的this JavaBrains个教程。
我的项目结构如下:
CourseApiApp.java :
@SpringBootApplication
@ComponentScan(basePackages = {
"com.bloodynacho.rishab.topics"
})
@EntityScan("com.bloodynacho.rishab.topics")
public class CourseApiApp {
public static void main(String[] args) {
SpringApplication.run(CourseApiApp.class, args);
}
}
TopicController.java :
@RestController
public class TopicController {
@Autowired
private TopicService topicService;
@RequestMapping(
value = "/topics"
)
public List<Topic> getAllTopcs() {
return topicService.getAllTopics();
}
}
TopicService.java :
@Service
public class TopicService {
@Autowired
private TopicRepository topicRepository;
public List<Topic> getAllTopics() {
List<Topic> topics = new ArrayList<>();
this.topicRepository
.findAll()
.forEach(topics::add);
return topics;
}
}
Topic.java :
@Entity
public class Topic {
@Id
private String id;
private String name;
private String description;
}
TopicRepository.java :
@Repository
public interface TopicRepository extends CrudRepository<Topic, String>{
}
pom.xml :
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
我在@Getter
中使用了龙目岛@Getter
,@AllArgsConstructor
和Topic.java
,但在阅读答案here中的一个后,我将其删除了。
还是,我知道
***************************
APPLICATION FAILED TO START
***************************
Description:
Field topicRepository in com.bloodynacho.rishab.topics.TopicService required a bean of type 'com.bloodynacho.rishab.topics.TopicRepository' 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.bloodynacho.rishab.topics.TopicRepository' in your configuration.
Process finished with exit code 1
编辑:我读过this,说明了即使没有实际实现@Autowired的接口也可以工作。我了解解决方案,但不了解如何解决问题。显然,Spring Data的设置和配置方式存在一些问题(如答案中所述)
答案 0 :(得分:2)
因为如果其他软件包层次结构都位于带有@SpringBootApplication
批注的主应用程序下面,则隐式组件扫描将覆盖您。
因此,可以通过以下两个步骤来完成一个简单的解决方案:
com.bloodynacho.rishab
。@ComponentScan
和@EntityScan
注释。@ComponentScan
与@EntityScan
不同,但根据我的经验也可以将其删除。)