java Autowire不适用于Spring Boot中的自定义UserDetails服务
spring boot应用程序启动,tomcat运行,然后抛出一个错误,最后死掉
错误
运行我的应用程序会出现以下Autowired
错误:
2016-07-29 02:18:24.737 ERROR 44715 --- [ restartedMain] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'webSecurityConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myapp.MyUserDetailsService myapp.WebSecurityConfig.userDetailsService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [myapp.MyUserDetailsService] 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)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
细节
我的安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
private MyUserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
}
MyUserDetails:
@Service
@Transactional
public class MyUserDetailsService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
public MyUserDetailsService() {
super();
}
@Override
public UserDetails loadUserByUsername(String userName)
throws UsernameNotFoundException {
User user = userRepository.findByUserName(userName);
if (user == null) {
return null;
}
List<GrantedAuthority> auth = AuthorityUtils
.commaSeparatedStringToAuthorityList("ROLE_USER");
String password = user.getPassword();
return new org.springframework.security.core.userdetails.User(userName, password,
auth);
}
}
你可以在Git Repo找到完整的源代码
# 1 楼答案
我在commit
3b9a6a2e
上尝试了您的项目,但错误实际上不同:这使你的问题与Spring can't create beans重复。解决方案:替换
与
您的解决方案(删除
@Transactional
)是有效的,因为如果没有@Transactional
,Spring就没有理由将MyUserDetailsService
包装在代理中# 2 楼答案
将
@ComponentScan
添加到WebSecurity配置由于component scanning,这应该连接到MyUserDetailsService,因为它是用
@Service
注释的包名可以作为参数传递给注释,以设置组件扫描的范围,例如:
# 3 楼答案
请添加注释:
@ComponentScan("")
在主配置类上如果您想为特定目录创建bean/service,那么您可以在
@ComponentScan("package.to.scan")
内提供包路径