Spring Security项目报错:需在配置中定义UserService类型Bean
Spring Security应用启动报错:
Consider defining a bean of type 'de.JBR.mongo.models.UserService' in your configuration 报错信息:
Consider defining a bean of type 'de.JBR.mongo.models.UserService' in your configuration.
我的Spring Boot启动类代码
@ComponentScan({ "de.JBR.mongo.repositry", "de.JBR.mongo.api.models", "security.config", "security"}) @EnableMongoRepositories("de.JBR.mongo") @SpringBootApplication @AllArgsConstructor public class EssensManagerApplication { private final UserRepositry repositry; public static void main(String[] args) { SpringApplication.run(EssensManagerApplication.class, args); } }
UserService类代码(de.JBR.mongo.models.UserService)
@AllArgsConstructor @Service public class UserService implements UserDetailsService{ private final static String USER_NOT_FOUND = "Nutzer mit Name %s nicht gefunden"; private final UserRepositry repositry; @Override @Bean public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repositry.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException(String.format(USER_NOT_FOUND, username))); } }
问题原因
UserService所在的de.JBR.mongo.models包不在启动类@ComponentScan的扫描范围内,Spring无法识别带有@Service注解的该类,无法将其注册为容器Bean。loadUserByUsername方法上错误添加了@Bean注解,该注解用于定义Bean的生成方法,而此处是实现UserDetailsService的接口方法,属于业务逻辑实现,不需要该注解。
解决方案
1. 修正组件扫描范围
将de.JBR.mongo.models加入@ComponentScan的扫描路径,修改后的启动类注解:
@ComponentScan({ "de.JBR.mongo.repositry", "de.JBR.mongo.api.models", "de.JBR.mongo.models", "security.config", "security"})
或者更简洁地直接扫描根包,覆盖所有子模块:
@ComponentScan({ "de.JBR", "security"})
另外,@SpringBootApplication本身默认包含组件扫描逻辑,会扫描启动类所在包及其子包。如果启动类位于de.JBR包下,甚至可以直接移除@ComponentScan注解,让Spring自动完成扫描。
2. 移除多余的@Bean注解
修改UserService的接口实现方法,去掉不必要的@Bean:
@AllArgsConstructor @Service public class UserService implements UserDetailsService{ private final static String USER_NOT_FOUND = "Nutzer mit Name %s nicht gefunden"; private final UserRepositry repositry; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { return repositry.findByUsername(username) .orElseThrow(() -> new UsernameNotFoundException(String.format(USER_NOT_FOUND, username))); } }
内容的提问来源于stack exchange,提问作者Jakob Ball
相关产品推荐
相关产品推荐

