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

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

Application.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

 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

 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 { List findBySiteName(String url); } 

我的服务控制器

 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 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"; } } 

这是我不断得到的错误。

  . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: 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] osbfsDefaultListableBeanFactory : 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] osbfsDefaultListableBeanFactory : 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] sbcetTomcatEmbeddedServletContainer : 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] oaccC[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2017-07-24 14:53:34.687 INFO 18060 --- [ost-startStop-1] osweb.context.ContextLoader : Root WebApplicationContext: initialization completed in 1711 ms 2017-07-24 14:53:34.838 INFO 18060 --- [ost-startStop-1] osbwservlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2017-07-24 14:53:34.842 INFO 18060 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2017-07-24 14:53:34.843 INFO 18060 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2017-07-24 14:53:34.843 INFO 18060 --- [ost-startStop-1] osbwservlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2017-07-24 14:53:34.843 INFO 18060 --- [ost-startStop-1] osbwservlet.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] osbdLoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: Field psRepo in Controller.ServicesController required a bean of type 'hello.provScoreRepo' that could not be found. Action: 

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

旁注,即时通讯使用eclipse STS。 这是我的文件夹层次文件夹层次结构真的很感激任何帮助。

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

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

这里几个错误:

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

对于@EntityScan也是@EntityScan :应该是@EntityScan("hello")而不是@EntityScan("hello.provScore")

@SpringBootApplication(scanBasePackages="hello.Application") 。 从某种意义上讲,没有更多的bean可以扫描和连接,但这个值应该是正确的@SpringBootApplication(scanBasePackages="hello")@SpringBootApplication ,它是等价的,因为默认是扫描基础包和子包。

最后,由于@SpringBootApplication是一个元注释(本身就意味着@ComponentScan), you could have - for simplicity - committed it and used @SpringBootApplication(scanBasePackages = {“hello”,“Controller”) . Don't know for what reason you have abandoned the . Don't know for what reason you have abandoned the该控制器. Don't know for what reason you have abandoned the hello`命名空间。

把它们放在一起,你应该尝试如下:

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

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

最后3天后。 问题基本上是依赖和hibernate。

  org.hibernate hibernate-entitymanager 4.1.4.Final   org.hibernate.javax.persistence hibernate-jpa-2.0-api 1.0.1.Final   org.hibernate hibernate-core 4.1.4.Final