1

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.

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

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

tahashanouha
  • 21
  • 1
  • 1
  • 3
  • Try to delete `@Component` annotation from 'repo' class. (And pls delete all unnecessary code: imports, logs...) – Cepr0 Jul 24 '17 at 14:14
  • @Cepr0 Deleted, still the same error. – tahashanouha Jul 24 '17 at 19:34
  • Check [this](https://stackoverflow.com/a/45166390) answer. – Cepr0 Jul 24 '17 at 19:39
  • Spring Boot is complicated. You are trying to customize the default structure without understanding how the framework works, which is why the errors. See [this sample](https://github.com/manish-in-java/stackoverflow-questions/tree/master/45282735) based on your code that works as expected. Customize it as you see fit, without changing the folder structure first. Then compare it to your code to see why your code is not working. – manish Jul 25 '17 at 04:00
  • @manish still no luck :/ – tahashanouha Jul 25 '17 at 12:55

4 Answers4

5

I had the same problem and used this :

@SpringBootApplication
@EnableJpaRepositories("repository")
@EntityScan("model")
Rania ZYANE
  • 49
  • 1
  • 3
2

Few errors here:

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

This goes as well for @EntityScan: should be @EntityScan("hello") and not @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 @SpringBootApplication which is equivalent since the default is to scan the base package and sub packages.

And lastly, since @SpringBootApplication is 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.

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)

Ori Dar
  • 18,687
  • 5
  • 58
  • 72
  • I would also Recommend not using lowercase Class names. This can be super confusing with Java code and highly accepted as a bad practice – Chad Jul 24 '17 at 14:17
  • Hello, thanks for your help. I am still however, getting the same error Description: Field psRepo in Controller.ServicesController required a bean named 'entityManagerFactory' that could not be found. Action: Consider defining a bean named 'entityManagerFactory' in your configuration. – tahashanouha Jul 24 '17 at 14:53
  • Please read spring boot tutorial JPA relevant stuff. This is beyond comment or even answer. The short answer is to add `spring-boot-starter-jpa` as a dependency to your Gradle/Maven/other dependency managment tool – Ori Dar Jul 24 '17 at 15:01
  • Can you post the whole sta ktrace? – Ori Dar Jul 24 '17 at 15:13
  • @OriDar Sorry, im new to this, how do you suggest doing so. What you see above is everything on the console. – tahashanouha Jul 24 '17 at 19:37
1

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

<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>
tahashanouha
  • 21
  • 1
  • 1
  • 3
0

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

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
Fahd Allebdi
  • 354
  • 4
  • 7