我正在学习Spring Boot,并且在运行应用程序时出现此错误 说明:
com.example.controller.UserController中的字段userRepository需要一个无法找到的“com.example.repository.UserRepository”类型的bean。
动作:
考虑在配置中定义'com.example.repository.UserRepository'类型的bean。
所有套餐
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);
}
}
我的日志是:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: 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.
我尝试了很多东西,但它仍然不起作用。
答案 0 :(得分:2)
尝试将@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就会自动配置它们。否则,您必须使用此批注手动指定包。
您还需要从控制器中删除@Repository
注释。 @Repository
只是另一个刻板印记注释,其别名为@Component
。
答案 1 :(得分:0)
可能你应该:
Start.java
的软件包(解决方案不好,但它对我有用,了解发生了什么)@EnableJpaRepositories
Start.java
@SpringBootApplication(scanBasePackages={"com.test.pkg"})
答案 2 :(得分:0)
您可以将模型,控制器和存储库软件包作为“ com.example”软件包的子软件包。
好像您的Start()类找不到兄弟程序包,但可以找到子程序包。
答案 3 :(得分:0)
这几乎不是一个解决方案,但是我在一个完整的早晨中追逐了它,最后在我的application.properties中发现了我不小心删除了MYSQL_HOST中的花括号。运行项目时,显示此线程中的错误,前面带有“ com.amazonaws.SdkClientException:无法连接到服务端点: 在com.amazonaws.internal.EC2ResourceFetcher.doReadResource(...)”。 因此,由于端点无法访问(在我的情况下是AWS RDS),项目开始到达异常,最终导致bean丢失。
所以我想我的意思是:检查每一步,是否遇到此错误。
答案 4 :(得分:0)
就我而言,我已经改变了
<dependency>
<groupId> org.springframework.data </groupId>
<artifactId> spring-data-jpa </artifactId>
</dependency>
为
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId> spring-boot-starter-data-jpa </artifactId>
</dependency>
从maven存储库添加所需的版本 (对我来说是2.4.0)