繁体   English   中英

使用Spring Security时,Spring Boot @Autowired存储库实例为null

[英]Spring boot @Autowired repository instance null when using spring security

我的情况是这样的:

我正在构建一个春季启动应用程序,当我在控制器中自动装配UserRepository时,它将对其进行初始化,并且当我尝试调用findByUserName方法时,一切正常。

用户控制器

@Controller    
@RequestMapping(path="/api/v1/users") 
public class UserController {

@Autowired 
private UserRepository userRepository;

@GetMapping(path="/{userName}")
public @ResponseBody AuthenticationDetails getUserByUsername(@PathVariable String userName) throws UserNotFoundException {

    User user = userRepository.findByUserName(userName);=
    ...
    }
}

创建控制器后,我需要使用Spring Security来保护控制器的路径,因此我在SecurityConfig类中添加了以下配置:

安全配置

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().disable().authorizeRequests()
            .antMatchers(HttpMethod.POST, "/login").permitAll().anyRequest().authenticated().and()
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                    UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(new JWTAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

}
...
}

现在,当我尝试将请求发布到/ login路径时,由于userRepository实例为null,因此我尝试通过调用findByUserName方法通过userRepository实例加载数据时,在CustomAuthenticationProvider类中得到了NullPointerException。

CustomAuthenticationProvider

public class CustomAuthenticationProvider implements AuthenticationProvider {

@Autowired 
private UserRepository userRepository;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    User userFromRepository = userRepository.findByUserName(authentication.getName().toLowerCase()); 
    ...
}

我的问题是这样的:

在应用程序运行时,bean的状态是否相同? 在应用程序加载时是否创建了bean?

为什么Spring Boot在我的控制器和同一应用程序中设法通过Bean自动装配实例,而在另一个类中却没有自动装配实例?

问题是您像这样创建new CustomAuthenticationProvider()创建CustomAuthenticationProvider ,因此它不是真正的spring bean,并且不能注入其字段。 您需要做的是定义CustomAuthenticationProvider bean,它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM