Spring Boot连接MongoDB时找不到UserRepository Bean的问题求助
Spring Boot 连接 MongoDB 遇到的 Bean 缺失及 404 问题
启动时的错误信息
Description: Field userRepo in com.universitem.service.Impl.UserDetailsServiceImpl required a bean of type 'com.universitem.repository.UserRepository' that could not be found. Action: Consider defining a bean of type 'com.universitem.repository.UserRepository' in your configuration.
application.properties 配置
spring.jpa.hibernate.ddl-auto=update spring.data.mongodb.uri= /includes the uri spring.data.mongodb.database=test spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration spring.jpa.properties.hibernate.globally_quoted_identifiers=true universitem.app.secret=UniversityToken universitem.expires.in=120000 refresh.token.expires.in=604800
核心代码片段
主启动类
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) @EnableJpaRepositories(basePackages = {"com.universitem.repository"}) public class UniversitemApplication { public static void main(String[] args) { SpringApplication.run(UniversitemApplication.class, args); } }
安全配置类
@Configuration @EnableWebSecurity @Data public class SecurityConfig { private UserDetailsServiceImpl userDetailsService; private JwtAuthenticationEntryPoint handler; public SecurityConfig(UserDetailsServiceImpl userDetailsService, JwtAuthenticationEntryPoint handler) { this.userDetailsService = userDetailsService; this.handler = handler; } @Bean public JwtAuthenticationFilter jwtAuthenticationFilter() { return new JwtAuthenticationFilter(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("HEAD"); config.addAllowedMethod("GET"); config.addAllowedMethod("PUT"); config.addAllowedMethod("POST"); config.addAllowedMethod("DELETE"); config.addAllowedMethod("PATCH"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } @Bean public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity .cors() .and().csrf().disable() .exceptionHandling().authenticationEntryPoint(handler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/comment/getAllUniversityComment{universityId}") .permitAll() .antMatchers(HttpMethod.GET, "/university/getAll") .permitAll() .antMatchers(HttpMethod.POST, "/userType/add") .permitAll() .antMatchers(HttpMethod.POST, "/universityType/add") .permitAll() .antMatchers(HttpMethod.GET, "/userType/getAll") .permitAll() .antMatchers("/userAuth/**") .permitAll() .anyRequest().authenticated(); httpSecurity.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } }
UserRepository
@Repository public interface UserRepository extends JpaRepository<User,Long> { User findByUserName(String userName); User findByUserMail(String userMail); }
UserDetailsServiceImpl
@Service public class UserDetailsServiceImpl implements UserDetailsService { @Autowired private UserRepository userRepo; @Override public UserDetails loadUserByUsername(String userMail) throws UsernameNotFoundException { User user =userRepo.findByUserMail(userMail); return JwtUserDetails.create(user); } public UserDetails loadUserById(Long userId) { User user = userRepo .findById(userId).get(); return JwtUserDetails.create(user); } }
pom.xml 依赖
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency> </dependencies>
尝试的操作及新问题
尝试在@SpringBootApplication中添加scanBasePackages配置:
@SpringBootApplication(scanBasePackages = {"com.universitem.repository"}, exclude = {SecurityAutoConfiguration.class})
修改后数据库能正常启动,但发送请求时Postman返回404 Not Found错误。
解决方案
1. 修正 MongoDB 与 JPA 的冲突
同时引入JPA和MongoDB依赖,但UserRepository继承JpaRepository却连接MongoDB是核心矛盾。MongoDB对应的Repository应继承MongoRepository:
@Repository public interface UserRepository extends MongoRepository<User,Long> { User findByUserName(String userName); User findByUserMail(String userMail); }
移除主启动类上的@EnableJpaRepositories,替换为MongoDB的Repository启用注解,并排除不必要的自动配置:
@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class}) @EnableMongoRepositories(basePackages = {"com.universitem.repository"}) public class UniversitemApplication { public static void main(String[] args) { SpringApplication.run(UniversitemApplication.class, args); } }
删除application.properties中JPA相关配置:
# 移除以下两行 # spring.jpa.hibernate.ddl-auto=update # spring.jpa.properties.hibernate.globally_quoted_identifiers=true
2. 修复组件扫描范围
之前仅扫描Repository包,导致Controller、Service等组件未被Spring管理,引发404。需扩大扫描范围到根包:
@SpringBootApplication(scanBasePackages = {"com.universitem"}, exclude = {SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class}) @EnableMongoRepositories(basePackages = {"com.universitem.repository"}) public class UniversitemApplication { public static void main(String[] args) { SpringApplication.run(UniversitemApplication.class, args); } }
若主启动类已在com.universitem包下,可省略scanBasePackages,Spring Boot默认扫描启动类所在包及子包。
3. 检查Controller配置
确认Controller类添加了@RestController或@Controller注解,请求路径与Postman发送的路径一致,比如/userAuth/**对应的Controller是否存在、路径是否正确。
内容的提问来源于stack exchange,提问作者Furkan Türkmen
相关产品推荐
相关产品推荐

