UserDetailsS​​ervice中自动装配的CrudRepository始终为null

时间:2014-08-27 20:43:45

标签: spring spring-security autowired

我是Spring-World的新手,我有Spring Security和JPA的Spring Boot应用程序。还有CrudRepository和UserDetailsS​​ervice,见下文

申请类

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

userDAO的

@Repository
public interface UserDao extends CrudRepository<User, Long> {
    public Collection<User> findByName(String name);
}

ApiUserDetailsS​​ervice

@Component
public class ApiUserDetailsService implements UserDetailsService {

    @Autowired
    private UserDao dao;

    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
        assert dao != null;
        ...
    }
}

安全配置

@Configuration
@EnableWebSecurity
public class HttpBasicAuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestCache().requestCache(new NullRequestCache());
        http.httpBasic();
        http.authorizeRequests().anyRequest().authenticated();
    }


    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(new ApiUserDetailsService());
    }
}

为什么Autowired dao总是为空?我做错了什么?

1 个答案:

答案 0 :(得分:8)

您正在手动创建ApiUserDetailsService

@Autowired
public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(new ApiUserDetailsService());
}

你想要的是:

@Configuration
@EnableWebSecurity
@EnableJpaRepositories(basePackages = {"your.package.dao"})
public class HttpBasicAuthConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.requestCache().requestCache(new NullRequestCache());
        http.httpBasic();
        http.authorizeRequests().anyRequest().authenticated();
    }

    // register ApiUserDetailsService as a bean  
    @Bean 
    public UserDetailsService apiUserDetailsService() {
        return new ApiUserDetailsService();      
    } 

    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws     Exception {
        // get the autowired bean from Spring
        auth.userDetailsService(apiUserDetailsService());
    }
}