有 Java 编程相关的问题?

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

JavaSpring找不到bean

我正在学习Spring,因为它似乎是一个非常强大的框架。我已经做了很多入门指南,现在我正在尝试使用this tutorial。在它里面,所有的类都放在同一个包中,但是为了让它更有趣,我尝试根据类(实体、控制器等)使用不同的包。在测试REST服务之前,我正要测试它,但在构建应用程序时出错。这就是我的项目的结构:

project structure

与本教程中的类唯一不同的是ServletInitializer标记,它与initializr utility一起出现(实际上我使用了STS附带的那一个,但它是相同的)。据我所知,这与问题无关,所以这门课的内容与问题无关

本教程的另一个细微差别是Application类在这里被称为RestServicesApplication,但内容是相同的

当我尝试构建应用程序(使用Gradle的bootRun而不是Maven)时,我收到以下错误消息:

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

Description:

Parameter 0 of method init in com.example.restservices.RestServicesApplication required a bean of type 'com.example.repository.AccountRepository' that could not be found.


Action:

Consider defining a bean of type 'com.example.repository.AccountRepository' in your configuration.

:bootRun FAILED

因此,我尝试用@Bean注释AccountRepository,但它给了我一个编译错误,表示该位置不允许该注释。接下来,我尝试使用@Component注释(也在BookmarkRepository)并在RestServicesApplication中添加@ComponentScan("com.example")。之后,错误仍然存在,但消息更改为

***************************
APPLICATION FAILED TO START
***************************
Description:

Parameter 0 of constructor in com.example.controller.BookmarkRestController required a bean of type 'com.example.repository.BookmarkRepository' that could not be found.

Action:

Consider defining a bean of type 'com.example.repository.BookmarkRepository' in your configuration.

:bootRun FAILED

我在BookmarkRestController中添加了@Component注释,但仍然存在相同的错误消息。我错过了什么

提前感谢您的回答


编辑#1

问题涉及的类如下(从我的项目中复制,而不是教程中的类,尽管差异很小):

RestServicesApplication

package com.example.restservices;

import java.util.Arrays;

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 com.example.entity.Account;
import com.example.entity.Bookmark;
import com.example.repository.AccountRepository;
import com.example.repository.BookmarkRepository;

@SpringBootApplication
@ComponentScan("com.example")
public class RestServicesApplication {

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

    @Bean
    CommandLineRunner init(final AccountRepository accountRepository,
            final BookmarkRepository bookmarkRepository) {
        return (evt) -> Arrays.asList(
                "jhoeller,dsyer,pwebb,ogierke,rwinch,mfisher,mpollack,jlong".split(","))
                .forEach(
                        a -> {
                            final Account account = accountRepository.save(new Account(a,
                                    "password"));
                            bookmarkRepository.save(new Bookmark(account,
                                    "http://bookmark.com/1/" + a, "A description"));
                            bookmarkRepository.save(new Bookmark(account,
                                    "http://bookmark.com/2/" + a, "A description"));
                        });
    }
}

BookmarkRestController

package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.repository.AccountRepository;
import com.example.repository.BookmarkRepository;

@RestController
@RequestMapping("/{userId}/bookmarks")
public class BookmarkRestController {

    private final BookmarkRepository bookmarkRepository;
    private final AccountRepository accountRepository;

    @Autowired
    public BookmarkRestController(final BookmarkRepository bookmarkRepository,
            final AccountRepository accountRepository) {
        this.bookmarkRepository = bookmarkRepository;
        this.accountRepository = accountRepository;
    }

    // @RequestMapping methods...
}

AccountRepository

package com.example.repository;

import java.util.Optional;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

import com.example.entity.Account;

@Component
public interface AccountRepository extends JpaRepository<Account, Long> {
    Optional<Account> findByUsername(String username);
}

BookmarkRepository

package com.example.repository;

import java.util.Collection;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

import com.example.entity.Bookmark;

@Component
public interface BookmarkRepository extends JpaRepository<Bookmark, Long> {
    Collection<Bookmark> findByAccountUsername(String username);
}

注意:我添加了导入,以便您可以查看类和注释的来源


编辑#2

我尝试了另一件事:我重构了我的项目以适应教程,我将所有内容都放在同一个包(com.example.bookmarks)中,并删除了额外的注释。该项目是编译的,但当我运行该项目时,在尝试访问REST服务时,我会获得404HTTP状态。我仍然对使用我的原始结构运行它感兴趣,但我想让您知道,这种重构使项目能够工作


共 (2) 个答案

  1. # 1 楼答案

    我认为您必须再次创建包。你的包装看起来不对劲。重新创建您的包

  2. # 2 楼答案

    要让Spring创建一个实现JpaRepository接口的bean,您需要使用SpringJPA名称空间并使用适当的元素激活存储库支持。在xml中:

    <jpa:repositories base-package="com.example.repository" />
    

    在注释中:

    @EnableJpaRepositories
    

    this docs

    这将扫描com.example.repository下面的所有包,以查找扩展JpaRepository的接口,并为其创建一个由SimpleJpaRepository实现支持的Springbean