Spring Boot启动报错:UserService依赖的UserRepository Bean未找到
Spring Boot启动报错:找不到UserRepository类型的Bean
我和团队在运行Spring Boot应用时接连踩坑,刚修复一个错误又冒出新问题,查了很多资料都没解决。
启动错误信息
Parameter 0 of constructor in com.earworm.backendearworm.UserService required a bean of type com.earworm.backendearworm.UserRepository that could not be found
我已经尝试过添加不同依赖,以下是相关代码:
UserService.java
package com.earworm.backendearworm; import java.time.LocalDateTime; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.UUID; import com.earworm.registration.token.ConfirmationToken; import com.earworm.registration.token.ConfirmationTokenService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class UserService implements UserDetailsService { private final UserRepository userRepository; private final BCryptPasswordEncoder bCryptPasswordEncoder; private final ConfirmationTokenService confirmationTokenService; public UserService(UserRepository userRepository, BCryptPasswordEncoder bCryptPasswordEncoder, ConfirmationTokenService confirmationTokenService) { this.userRepository = userRepository; this.bCryptPasswordEncoder = bCryptPasswordEncoder; this.confirmationTokenService = confirmationTokenService; } public List<User> getUsers() { return userRepository.findAll(); } public String addNewUser(User user) { Optional<User> userByEmail = userRepository.findUserByEmail(user.getEmail()); if (userByEmail.isPresent()) { throw new IllegalStateException("Email taken"); } String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword()); user.setPassword(encodedPassword); userRepository.save(user); String token = UUID.randomUUID().toString(); ConfirmationToken confirmationToken = new ConfirmationToken(token, LocalDateTime.now(), LocalDateTime.now().plusMinutes(15), user); confirmationTokenService.saveConfirmationToken(confirmationToken); return token; } /* * Fix exists by ID by actually passing id and changing repository from string * to long */ public void deleteUser(Long id) { boolean userExists = userRepository.existsById(id); if (!userExists) { throw new IllegalStateException("User with id " + id + " does not exist"); } userRepository.deleteById(id); } // Name and email are optional @Transactional public void updateUser(Long id, String username, int zipCode, String bio) { User user = userRepository.findById(id) .orElseThrow(() -> new IllegalStateException("User with id " + id + " does not exist")); if (username != null && username.length() > 0 && !Objects.equals(user.getUsername(), username)) { user.setUsername(username); } // -------Change email if wanted------- // if (email != null && email.length() > 0 && !Objects.equals(user.getEmail(), // email)) { // Optional<User> userOptional = userRepository.findUserByEmail(email); // if (userOptional.isPresent()) { // throw new IllegalStateException("Email taken"); // } // user.setEmail(email); // } // Fix to lang and // long?>---------------------------------------------------------------------------------- // user.setZipCode(zipCode); user.setBio(bio); } /* @Override public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException { return userRepository.findUserByEmail(email) .orElseThrow(() -> new UsernameNotFoundException("user with email " + email + " not found")); } public int enableUser(String email) { return userRepository.enableUser(email); } */ @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { // TODO Auto-generated method stub return null; } }
UserRepository.java
package com.earworm.backendearworm; import java.util.List; import java.util.Optional; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; public interface UserRepository extends JpaRepository<User, Long> { @Query("SELECT s FROM User s WHERE s.email = ?1") Optional<User> findUserByEmail(String email); // List<User> findAllByZipcode(int zipCode); // @Query("SELECT s FROM User s WHERE s.username = ?1") Optional<User> existsByUsername(String username); @Transactional @Modifying @Query("UPDATE user a " + "Set a.enabled = TRUE WHERE a.email = ?1") int enableUser(String email); }
解决办法
针对这个报错,按以下步骤排查:
- 给UserRepository添加@Repository注解:当前UserRepository接口只是导入了@Repository但未实际标注,Spring无法将其识别为可注入的Bean。修改后代码如下:
@Repository public interface UserRepository extends JpaRepository<User, Long> { // 原有方法保持不变 } - 检查Spring Boot主类的包扫描范围:确保主类所在的包是
com.earworm或更上层(比如com),这样Spring会自动扫描子包com.earworm.backendearworm下的组件。如果主类在更深的子包,需要在主类上添加@ComponentScan(basePackages = "com.earworm")指定扫描范围。 - 确认JPA依赖已正确引入:检查项目的构建文件(pom.xml或build.gradle),确保包含spring-boot-starter-data-jpa依赖:
<!-- Maven示例 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> - 检查User实体类配置:确保User类添加了
@Entity注解,并且主键字段标注了@Id(及@GeneratedValue),否则JPA无法为Repository生成代理实现类。
内容的提问来源于stack exchange,提问作者Rodolfo
相关产品推荐
相关产品推荐

