【发布时间】:2020-01-20 03:54:19
【问题描述】:
我在包上有一个 Repository 类:
com.repository
我已经在 Spring Boot 的主类中定义了@ComponentScan("com.*")。
但是在运行应用程序时我得到了异常
考虑定义一个“com.repository.TopicRepository”类型的bean 你的配置。
以下是类:
主题库
package com.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.models.Topic;
@Repository
public interface TopicRepository extends CrudRepository<Topic,String>{
}
应用程序
package com.example.springboot.springboot.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.*")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
POM.xml
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.3.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.springboot</groupId>
<artifactId>springboot.test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot.test</name>
<description>Demo project for Spring Boot</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<properties>
<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
我已经尝试过@ComponentScan。如果我将scanBasePackages 更改为"com.repository",那么它能够以某种方式拾取TopicRepository 以及其他Service and Controller,这不应该是这种情况,因为它们在不同的包下。
编辑:
包结构
com.models : 模型
com.repository : 存储库
com.services : 服务
com.controllers : 控制器
com.springboot.springboottest : 主类
【问题讨论】:
-
包规范不是一个整体;只需使用
com。 -
你试过@ComponentScan("com") 吗?或@SpringBootApplication(scanBasePackages="com")
-
如果所有要扫描的类都保存在主类的子包下,用户甚至不需要提包名
标签: java spring eclipse spring-boot