为什么我在运行在配置中定义“com.exam.repo.UserRepository”类型 bean 的 Spring Boot 应用程序时遇到错误?

问题描述 投票:0回答:1
package com.exam.examserver;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ImportResource;

import com.exam.models.Role;
import com.exam.models.User;
import com.exam.models.UserRole;
import com.exam.service.UserService;

@ComponentScan({"com.exam.service"})
@SpringBootApplication
public class ExamserverApplication implements CommandLineRunner {

    @Autowired
    private UserService userService ;
    
    public static void main(String[] args) {
        SpringApplication.run(ExamserverApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("starting");     
        
        User user=new User();
        user.setFirstName("yogender");
        user.setLastName("sharma");
        user.setUserName("yogen139");
        user.setPassword("abc");
        user.setEmail("[email protected]");
 
        Role role1= new Role();
        role1.setRoleId(44L);
        role1.setRoleName("Admin");
        
        
        Set<UserRole> userRoleSet= new HashSet<>();
        UserRole userRole= new UserRole();
        userRole.setRole(role1);
        userRole.setUser(user);
        User user1= this.userService.CreateUser(user, userRoleSet);
        
        System.out.println(user1.getUserName());
    }
}

`Error starting ApplicationContext. To display the condition 
evaluation report re-run your application with 'debug' enabled.

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

Description:
Field userRepo in com.exam.service.UserServiceImpl required a bean 
of type 'com.exam.repo.UserRepository' 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.exam.repo.UserRepository' in 
your configuration.`

当我尝试运行应用程序时,我的控制台中出现此错误。我已经使用 @Repository 表示法定义了用户存储库。这是项目结构:

(https://i.stack.imgur.com/j5Lqg.png)

如果有人可以帮助我。

我正在 SpringToolSuite 上运行它并使用 MySQL 数据库。在那里执行了各种故障排除步骤。

java database spring-boot spring-annotations spring-repositories
1个回答
0
投票

该错误来自错误的扫描配置。默认情况下,Spring Boot 会扫描主类下面的所有包。由于您的主类位于“子”包中,因此它不会扫描所有其他类。

有 2 种方法可以修复它:

  1. 最简单的就是将主类一包上移,去掉
    @ComponentScan
    注解
  2. 或者,您需要将要扫描的所有包裹添加到
    @ComponentScan
    ,例如:
@ComponentScan({"com.exam.service","com.exam.repo","com.exam.models"})
© www.soinside.com 2019 - 2024. All rights reserved.