自Spring安全性从XML迁移到JavaConfig以来,UserDetailsS​​ervice缺少

时间:2014-02-20 19:19:19

标签: spring-security spring-java-config

我使用Spring Security 3.2.0.RELEASE

我目前正在将我的应用程序基于XML的Spring Security配置迁移到基于 JavaConfig 的Spring Security配置。

在旧的security.xml中,我按照以下方式配置了基于 JDBC UserDetailsService

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <password-encoder ref="passwordEncoder" />
        <!-- parsed by JdbcUserServiceBeanDefinitionParser -->
        <!-- the following creates a JdbcUserDetailsManager -->
        <jdbc-user-service data-source-ref="dataSource" />
    </authentication-provider>
</authentication-manager>

在其他影响中,上面的XML配置自动注册了一个类型为JdbcUserDetailsManager 的Spring Bean(UserDetailsService 的子类型,我可以注入进入其他组成部分:

@Service
public class MyCustomService {

    @Inject
    private JdbcUserDetailsManager judm;

    //...
}

基于我的 JavaConfig 的上述XML的适应性如下所示:

@Configuration
// @ImportResource("classpath:to/no/longer/needed/security.xml")
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .jdbcAuthentication()
            .passwordEncoder( somePasswordEncoder )
            .dataSource( someDataSource );
    }

    // ...
}

以上JavaConfig配置似乎没有另外注册类型为JdbcUserDetailsManager 的Spring Bean。这意味着MyCustomService没有注入这样的bean,因此我得到NoSuchBeanDefinitionException

 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.security.provisioning.JdbcUserDetailsManager] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@javax.inject.Inject()}

使用JavaConfig方法,如何获取JdbcUserDetailsManager类型的bean?

1 个答案:

答案 0 :(得分:0)

你试过添加

吗?
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(){
    return new JdbcUserDetailsManager();
}

到您的SecurityConfig类?