2

I'm learning Spring Boot and I get this error when a run the app Description:

Field userRepository in com.example.controller.UserController required a bean of type 'com.example.repository.UserRepository' that could not be found.

Action:

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

All packages

enter image description here

Start.java

    package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

User.java

package com.example.model;

import org.springframework.data.annotation.Id;

public class User {
    @Id
    private String id;
    private String name;
    private int age;
    private String email;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

UserRepository.java

    package com.example.repository;

    import org.springframework.data.mongodb.repository.MongoRepository;

    import com.example.model.User;

    public interface UserRepository extends MongoRepository<User, String>{

        public User findOneBy(String name);

    }

UserController.java

package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.User;
import com.example.repository.UserRepository;

@Repository("com.example.repository")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserRepository userRepository;

    //Create
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void createUser(@RequestBody User user){
        userRepository.save(user);
    }

    //Read
    @RequestMapping(value ="/{id}")
    public User readUser(@PathVariable String id){
        return userRepository.findOneBy(id);
    }

    //Update
    @RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
    public void updateUser(User user){
        userRepository.save(user);
    }

    //Delete
    @RequestMapping(value ="/{id}", method = RequestMethod.DELETE)
    public void deleteUser(String id){
        userRepository.deleteById(id);
    }

}

My log is:

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

2017-10-20 13:23:13.420  INFO 6060 --- [           main] com.example.Start                        : Starting Start on ANDRES-CASTANEDA with PID 6060 (C:\Users\andres.castaneda\Desktop\SpringBootMongoDB\SpringBootMongoDB\bin started by andres.castaneda in C:\Users\andres.castaneda\Desktop\SpringBootMongoDB\SpringBootMongoDB)
2017-10-20 13:23:13.422  INFO 6060 --- [           main] com.example.Start                        : No active profile set, falling back to default profiles: default
2017-10-20 13:23:13.471  INFO 6060 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6b0c2d26: startup date [Fri Oct 20 13:23:13 COT 2017]; root of context hierarchy
2017-10-20 13:23:14.635  INFO 6060 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-10-20 13:23:14.647  INFO 6060 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-10-20 13:23:14.648  INFO 6060 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.23
2017-10-20 13:23:14.769  INFO 6060 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-10-20 13:23:14.769  INFO 6060 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1302 ms
2017-10-20 13:23:14.922  INFO 6060 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-10-20 13:23:14.925  INFO 6060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-10-20 13:23:14.926  INFO 6060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-10-20 13:23:14.926  INFO 6060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-10-20 13:23:14.926  INFO 6060 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-10-20 13:23:14.961  WARN 6060 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
2017-10-20 13:23:14.963  INFO 6060 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2017-10-20 13:23:14.976  INFO 6060 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2017-10-20 13:23:15.077 ERROR 6060 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field userRepository in com.example.controller.UserController required a bean of type 'com.example.repository.UserRepository' that could not be found.


Action:

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

I have tried many things but it still doesn't work.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Is your `Start` class really in that package? Spring Boot scans for `MongoRepository` types in the same package or "subpackages" as the `@SpringBootApplication` annotated class. You can customize where it searches with `@EnableMongoRepositories`. – Sotirios Delimanolis Oct 20 '17 at 18:10

5 Answers5

2

Try adding @EnableMongoRepositories to your application class, e.g.:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@EnableMongoRepositories("com.example.repopackage")
public class Start {
    public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }
}

As long as your MongoRepository extensions are in packages underneath your application class' package, then Spring will auto-configure them. Otherwise, you have to specify the package manually using this annotation.

You'll also want to remove the @Repository annotation from your controller. @Repository is just another stereotype annotation that aliases to @Component.

Brian
  • 17,079
  • 6
  • 43
  • 66
  • Without more log information, I can't really help you then. Can you get full stack traces from your logs and add them to your question? Make sure you grab all of them in case there's a connectivity issue with MongoDB that's causing your issue. – Brian Oct 20 '17 at 18:41
0

Probably, you should:

  • Move all your files in to the package that contains Start.java (bad solution, but it worked for me to understand what happening)
  • Use the annotation @EnableJpaRepositories in Start.java
  • Play with @SpringBootApplication(scanBasePackages={"com.test.pkg"})
Max Gabderakhmanov
  • 912
  • 1
  • 18
  • 36
0

You can make your model, controller and repository packages as sub packages to your "com.example" package.

Seems like your Start() class cannot find sibling packages, but it can find children packages.

gmhafiz
  • 3
  • 1
  • 1
0

This is hardly a solution, but I chased this for a full morning and in the end, turns out in my application.properties I accidentally deleted the curly braces in the MYSQL_HOST. When running the project, the error in this thread was shown, preceded by "com.amazonaws.SdkClientException: Failed to connect to service endpoint: at com.amazonaws.internal.EC2ResourceFetcher.doReadResource (...)". So, since the endpoint wasn't reachable (in my case, AWS RDS), the project started reaching exceptions that eventually led to the bean missing.

So I guess what I'm saying is: check every step if you're getting this error.

bupereira
  • 1,463
  • 8
  • 13
0

For my part, I have changed

<dependency>
        <groupId> org.springframework.data </groupId>
        <artifactId> spring-data-jpa </artifactId>
</dependency>

for

<dependency>
     <groupId> org.springframework.boot </groupId>
     <artifactId> spring-boot-starter-data-jpa </artifactId>
</dependency>

Add the version that you want from maven repository ( 2.4.0 for me)

L.Charly
  • 41
  • 5