英文:
Java Spring: @Autowired (Field repository in Controller required a bean named Repository that could not be found.)
问题
我尝试将我的Java Spring应用与PostgreSQL连接。不幸的是,在使用@Autowired时收到错误消息:“Controller中的字段repository需要一个名为Repository的bean,但找不到该bean。”
Controller.java
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
Repository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
JpaConfig.java
@Configuration
public class JpaConfig {
}
pom.xml
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
英文:
I try to connect my Java Spring app with PostgreSQL. Unfortunately I receive an error while using @Autowired: "Field repository in Controller required a bean named Repository that could not be found."
Controller.java
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
<!-- end snippet -->
Repository.java
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
<!-- end snippet -->
JpaConfig.java
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
@Configuration
public class JpaConfig {
}
<!-- end snippet -->
pom.xml
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.12</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- end snippet -->
Do you have any idea what's the problem here? I appreciate your help.
专注分享java语言的经验与见解,让所有开发者获益!
评论