有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法自动连线。未找到“NoteRepository”类型的bean

下面是我的控制器类

@Controller
public class app {

    @GetMapping(path = "/")
    public @ResponseBody
    String hello() {
        return "Hello app";
    }
}

当我在url中导航时,它运行良好。但当添加下面的代码时,它会显示"Could not autowire. No beans of 'NoteRepository' type found"

@Autowired
    NoteRepository noteRepository;

    // Create a new Note
    @PostMapping("/notes")
    public Note createNote(@Valid @RequestBody Note note) {
        return noteRepository.save(note);
    }

App controller类位于主类(运行应用程序)所在的相同包中。但当我们将上述代码添加到不同包中的控制器时,它不会显示错误。但当我们浏览url时,即使是一个简单的get方法,它也不起作用

我的主课在下面

@SpringBootApplication
@EnableJpaAuditing
public class CrudApplication {

    public static void main(String[] args) {
        SpringApplication.run(CrudApplication.class, args);
    }
}

我的存储库类是

@Repository
public interface NoteRepository extends JpaRepository<Note, Long> {
}

我的项目结构

Image 1

我想找到解决方案:

  1. 注入NoteRepository的实例。我总是收到消息“无法自动连线。找不到类型的bean”错误。Spring不能注入它,不管接口是在同一个包中还是在不同的包中

  2. 我无法在控制器(MyController)中运行与应用程序入口点位于不同包中的方法

enter image description here


共 (2) 个答案

  1. # 1 楼答案

    您应该为spring添加包来扫描它们

    @SpringBootApplication(scanBasePackages={"package1", "package2"})
    
  2. # 2 楼答案

    主要症状是:

    App controller class is in the same package where main class(which run the application) is. but when we add above code to a controller in different package it doesn't show error. but it doesn't work when we navigate through url even a simple get method.

    默认情况下,Spring引导应用程序将只自动发现在主类之外的同一包中声明的bean。对于不同包中的bean,需要指定包含它们。您可以使用^{}进行此操作

    package foo.bar.main;
    
    //import statements....
    
    //this annotation will tell Spring to search for bean definitions
    //in "foo.bar" package and subpackages.
    @ComponentScan(basePackages = {"foo.bar"})
    @SpringBootApplication
    @EnableJpaAuditing
    public class CrudApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(CrudApplication.class, args);
        }
    }
    
    
    
    package foo.bar.controller;
    
    //import statements....
    
    //since @ComponentScan, now this bean will be discovered
    @Controller
    public class app {
    
        @GetMapping(path = "/")
        public @ResponseBody
        String hello() {
            return "Hello app";
        }
    }
    

    为了让Spring数据识别应该创建哪些存储库,您应该向主类添加@EnableJpaRepositories注释。另外,为了让Spring数据和JPA实现扫描实体,添加@EntityScan

    @ComponentScan(basePackages = {"foo.bar"})
    @SpringBootApplication
    @EnableJpaAuditing
    @EnableJpaRepositories("your.repository.packagename")
    @EntityScan("your.domain.packagename")
    public class CrudApplication {
        //code...
    }