【发布时间】:2016-10-03 21:09:33
【问题描述】:
我正在尝试使用 Spring Boot 配置数据源,但收到 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mycompany.myapp.repository.UserRepository com.mycompany.myapp.service.AuthenticationServiceImpl.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mycompany.myapp.repository.UserRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
这是我的项目结构:
主类:
package com.mycompany.myapp;
@ComponentScan(basePackageClasses = {com.mycompany.myapp.domain.user.User.class,
com.mycompany.myapp.repository.UserRepository.class,
com.mycompany.myapp.service.AuthenticationServiceImpl.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
领域类:
package com.mycompany.myapp.domain.user
@Entity
public class User {
@Id
@GeneratedValue
private long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String lastName;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private String email;
public User() {}
public User(String email, String password){
this.email = email;
this.password = password;
}
}
存储库:
package com.mycompany.myapp.repository;
public interface UserRepository extends CrudRepository<User, Long> {
List<User> findByLastName(String lastName);
}
控制器
package com.mycompany.myapp.service;
@RestController
public class AuthenticationServiceImpl implements AuthenticationService {
@Autowired
private UserRepository userRepository;
@RequestMapping("/add")
public User add(){
User user = new User();
user.setName("Juan");
user.setLastName("Sarpe");
user.setEmail("email@gmail.com");
userRepository.save(user);
return user;
}
}
application.properties
spring.datasource.url:jdbc:mysql://localhost:3306/mydb
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
我猜我的应用程序没有在 UserRepository 上检测到我的 @Repository 注释。据我所知,Spring Boot 会自动将我的类设置为@Repository,因为它扩展了 CrudRepository。我究竟做错了什么? (请注意,我的 Application 类位于包层次结构的顶部)。
【问题讨论】:
-
对我来说看起来不错。这就是例外吗?任何嵌套异常?检查另一个具有相同名称的类 (UserRepository)。你有正确的 maven/gradle 依赖吗?看看这个指南:spring.io/guides/gs/accessing-data-jpa
-
ar.com.prokarma.tim.repository.UserRepository这是一个单独的类吗? -
对不起,我已经复制了代码和异常并尝试运行它。我已经编辑了描述。我会将堆栈跟踪之前的异常添加到描述中。
-
您在 Application 类上缺少 @SpringBootApplication。请参考Spring documentation,因为包结构非常重要。
-
抱歉,我已经尝试在我的主课上设置
@SpringBootApplication。但它不会识别我的@Repository。这就是我尝试这样设置的原因..
标签: spring spring-boot spring-data spring-data-jpa