eclipse Spring Field 需要一个无法找到 Spring JPA 类型的 bean

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45282735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 23:27:26  来源:igfitidea点击:

Spring Field required a bean of type that could not be found Spring JPA

javaspringeclipsespring-bootspring-data-jpa

提问by tahashanouha

this is my first question on the forum since I'm pretty much stuck at a dead end. Im using spring to develop a restful web service, and in that service I wanna store some data in a db using spring data. However, after following the tutorial on the website and my getting started guides, I keep getting into similar problems, it seems that these tutorials always have something missing. Here is my code.

这是我在论坛上的第一个问题,因为我几乎陷入了死胡同。我使用 spring 开发了一个安静的 web 服务,在那个服务中,我想使用 spring 数据在数据库中存储一些数据。但是,按照网站上的教程和我的入门指南之后,我不断遇到类似的问题,似乎这些教程总是缺少一些东西。这是我的代码。

Application.java

应用程序.java

package hello;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;



@SpringBootApplication(scanBasePackages="hello.Application")
@EnableJpaRepositories("hello.provScoreRepo")
@ComponentScan("Controller")
@EntityScan("hello.provScore")

public class Application {

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


}

provScore.java

provScore.java

package hello;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class provScore {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String siteName;
    private double score;

    protected provScore() {}

    public provScore(String siteName, double score) {
        this.siteName = siteName;
        this.score = score;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, siteName='%s', score='%d']",
                id, siteName, score);
    }

}

provScoreRepo.java

provScoreRepo.java

package hello;

import java.util.List;

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

@Component
public interface provScoreRepo extends CrudRepository<provScore, Long> {

    List<provScore> findBySiteName(String url);
}

my services controller

我的服务控制器

package Controller;

import java.io.File;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import org.openprovenance.prov.interop.InteropFramework;
import org.openprovenance.prov.interop.InteropFramework.ProvFormat;
import org.openprovenance.prov.interop.*;
import org.openprovenance.prov.model.Document;
import org.openprovenance.prov.template.Bindings;
import org.openprovenance.prov.template.BindingsJson;
import org.openprovenance.prov.template.Expand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import hello.Greeting;
import hello.ProcessProv;
import hello.metaExtractor;
import hello.provScore;
import hello.provScoreRepo;

@RestController
public class ServicesController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();
    private final String provenanceExpanded = "provenanceExpanded.provn";

    @Autowired
    private provScoreRepo psRepo;
    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(counter.incrementAndGet(),
                            String.format(template, name));
    }

    @RequestMapping("/provrank/extract")
    public String extract(@RequestParam(value="url", defaultValue="http://www.dailymail.co.uk") String url) {
        metaExtractor me = new metaExtractor(InteropFramework.newXMLProvFactory(), url, "");
        if(me.extract(url, me))
        {
            if(process(provenanceExpanded,url))
            {
                return "Provenance Score of "+url+" has been stored in the db. To view call the Display service.";
            }
        }
        return "An error has occured";
    }

    @RequestMapping("/provrank/process")
    private boolean process(@RequestParam(value="filename",defaultValue="provenanceExpanded.provn") String filename,String url){
        ProcessProv processor = new ProcessProv(InteropFramework.newXMLProvFactory(),filename,url);
        return processor.process(processor);

    }
    @RequestMapping(path="/provrank/display")
    public @ResponseBody Iterable<provScore> getAllScores() {
        // This returns a JSON or XML with the users
        return psRepo.findAll();
    }
    @RequestMapping(path="/provrank/add") // Map ONLY GET Requests
    public @ResponseBody String addNewUser (@RequestParam String siteName
            , @RequestParam double score) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        provScore ps = new provScore(siteName,score);
        psRepo.save(ps);
        return "Saved";
    }


}


Here is the error that I keep getting.

这是我不断收到的错误。

 .   ____          _            __ _ _
 /\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2017-07-24 14:53:32.903  INFO 18060 --- [           main] hello.Application                        : Starting Application on DESKTOP-QL5T7CJ with PID 18060 (started by Taha Shanouha in C:\Users\Taha Shanouha\workspace\gs-rest-service-complete)
2017-07-24 14:53:32.906  INFO 18060 --- [           main] hello.Application                        : No active profile set, falling back to default profiles: default
2017-07-24 14:53:32.979  INFO 18060 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@29176cc1: startup date [Mon Jul 24 14:53:32 BST 2017]; root of context hierarchy
2017-07-24 14:53:33.702  INFO 18060 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'dataSource' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Dbcp; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Dbcp.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat; factoryMethodName=dataSource; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]]
2017-07-24 14:53:33.726  INFO 18060 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'httpRequestHandlerAdapter' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.data.rest.webmvc.config.RepositoryRestMvcConfiguration; factoryMethodName=httpRequestHandlerAdapter; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/data/rest/webmvc/config/RepositoryRestMvcConfiguration.class]]
2017-07-24 14:53:34.239  INFO 18060 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$b7d21d37] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-24 14:53:34.542  INFO 18060 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-24 14:53:34.551  INFO 18060 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-07-24 14:53:34.552  INFO 18060 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-07-24 14:53:34.687  INFO 18060 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-07-24 14:53:34.687  INFO 18060 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1711 ms
2017-07-24 14:53:34.838  INFO 18060 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-24 14:53:34.842  INFO 18060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-24 14:53:34.843  INFO 18060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-24 14:53:34.843  INFO 18060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-24 14:53:34.843  INFO 18060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-24 14:53:34.885  WARN 18060 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'servicesController': Unsatisfied dependency expressed through field 'psRepo'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'hello.provScoreRepo' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-07-24 14:53:34.887  INFO 18060 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2017-07-24 14:53:34.899  INFO 18060 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-07-24 14:53:34.999 ERROR 18060 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field psRepo in Controller.ServicesController required a bean of type 'hello.provScoreRepo' that could not be found.


Action:

Consider defining a bean of type 'hello.provScoreRepo' in your configuration.

考虑在您的配置中定义一个“hello.provScoreRepo”类型的 bean。

Side note, im using eclipse STS. Here is my folder hierarchy folder hierarchyWould really appreciate any help.

旁注,我正在使用 Eclipse STS。这是我的文件夹层次结构 文件夹层次结构非常感谢任何帮助。

回答by Rania ZYANE

I had the same problem and used this :

我遇到了同样的问题并使用了这个:

@SpringBootApplication
@EnableJpaRepositories("repository")
@EntityScan("model")

回答by Ori Dar

Few errors here:

这里的错误很少:

First, @EnableJpaRepositoriesexpects base package name and not classes, so it's value should be helloand not hello.provScoreRepo

首先,@EnableJpaRepositories需要基本包名而不是类,所以它的值应该是hello而不是hello.provScoreRepo

This goes as well for @EntityScan: should be @EntityScan("hello")and not @EntityScan("hello.provScore")

这也适用于@EntityScan:应该@EntityScan("hello")和不@EntityScan("hello.provScore")

And @SpringBootApplication(scanBasePackages="hello.Application"). It's not erroneous in the sense that there's no more beans to scan and wire, but the value should be for correctness @SpringBootApplication(scanBasePackages="hello")or @SpringBootApplicationwhich is equivalent since the default is to scan the base package and sub packages.

并且@SpringBootApplication(scanBasePackages="hello.Application")。从没有更多的 bean 需要扫描和连接的意义上来说,这并没有错,但该值应该是为了正确性@SpringBootApplication(scanBasePackages="hello")@SpringBootApplication等效,因为默认值是扫描基本包和子包。

And lastly, since @SpringBootApplicationis a meta annotation (by itself implies @ComponentScan), you could have - for simplicity - committed it and used@SpringBootApplication(scanBasePackages={"hello", "Controller"). Don't know for what reason you have abandoned thehello` namespace for that controller.

最后,因为@SpringBootApplication是元注解(它本身意味着@ComponentScan), you could have - for simplicity - committed it and used@SpringBootApplication(scanBasePackages={"hello", "Controller") . Don't know for what reason you have abandoned thehello`控制器的命名空间。

Putting it all together, you should try something such as:

综合起来,您应该尝试以下操作:

@SpringBootApplication(scanBasePackages={"hello", "Controller"})
@EnableJpaRepositories("hello")
@EntityScan("hello")

Finally, for naming convention, you should call the package controller(lowercase c)

最后,对于命名约定,您应该调用包controller(小写c

回答by tahashanouha

Finally after 3 days. The problem was basically with the dependencies and hibernate.

终于在3天后。问题基本上与依赖项和休眠有关。

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>4.1.4.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

回答by Fahd Allebdi

I had same issue , i changed spring boot version and solved.

我遇到了同样的问题,我更改了 Spring Boot 版本并解决了。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>