我正在学习 Spring Boot,运行应用程序时出现此错误 说明:
Field userRepository in com.example.controller.UserController required a bean of type 'com.example.repository.UserRepository' that could not be found.
行动:
考虑在您的配置中定义“com.example.repository.UserRepository”类型的 bean。
所有包
启动.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);
}
}
用户.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);
}
}
我的日志是:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: 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.
我尝试了很多方法,但还是不行。
最佳答案
尝试添加 @EnableMongoRepositories
到您的应用程序类,例如:
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);
}
}
只要您的 MongoRepository
扩展位于应用程序类包下的包中,Spring 就会自动配置它们。否则,您必须使用此注释手动指定包。
您还需要从 Controller 中删除 @Repository
注释。 @Repository
只是另一个别名为 @Component
的构造型注释。
关于java - com.example.controller.UserController 中的字段 userRepository 需要类型为 'com.example.repository.UserRepository' 的 bean,但无法找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46854773/