2017-10-20 4 views
1

J'apprends Spring Boot et j'obtiens cette erreur quand un run l'application Description :Field userRepository dans com.example.controller.UserController requis un bean de type 'com.example.repository.UserRepository' qui n'a pas pu être trouvé

terrain userRepository dans com.example.controller.UserController requis un bean de type 'com.example.repository.UserRepository' qui n'a pas pu être trouvé.

Action:

Tenir compte définir un bean de type 'com.example.repository.UserRepository' dans votre configuration.

Tous les forfaits

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

} 

Mon journal est:

. ____   _   __ _ _ 
/\\/___'_ __ _ _(_)_ __ __ _ \ \ \ \ 
(()\___ | '_ | '_| | '_ \/ _` | \ \ \ \ 
\\/ ___)| |_)| | | | | || (_| | )))) 
    ' |____| .__|_| |_|_| |_\__, |//// 
=========|_|==============|___/=/_/_/_/ 
:: 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[email protected]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. 

J'ai essayé beaucoup de choses, mais il ne fonctionne toujours pas.

+0

Est-ce que votre classe 'Start' est vraiment dans ce paquet? Spring Boot analyse les types 'MongoRepository' dans le même paquet ou les 'sous-paquetages' que la classe annotée' @ SpringBootApplication'. Vous pouvez personnaliser l'endroit où il recherche avec '@ EnableMongoRepositories'. –

Répondre

1

Essayez d'ajouter @EnableMongoRepositories à votre classe d'application, par exemple .:

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

Tant que vos MongoRepository extensions sont en paquets sous votre package de classe d'application, puis Spring leur configurer automatiquement. Sinon, vous devez spécifier le paquet manuellement en utilisant cette annotation.

Vous devez également supprimer l'annotation @Repository de votre contrôleur. @Repository est juste une autre annotation de stéréotype qui alias @Component.

+0

Cela ne fonctionne toujours pas –

+0

Sans plus d'informations de journal, je ne peux pas vraiment vous aider alors.Pouvez-vous obtenir des traces complètes de vos journaux et les ajouter à votre question? Assurez-vous de les récupérer au cas où il y aurait un problème de connectivité avec MongoDB qui causera votre problème. – Brian

0

Probablement, vous devez:

  • Déplacer tous vos fichiers dans le package qui contient Start.java (mauvaise solution, mais cela a fonctionné pour moi de comprendre ce qui se passe)
  • Utilisez l'annotation @EnableJpaRepositories dans Start.java
  • Jouer avec @SpringBootApplication(scanBasePackages={"com.test.pkg"})