我的情况是这样的:
我正在构建一个 Spring Boot 应用程序,当我在 Controller 中 Autowiring UserRepository 时,它会初始化它,当我尝试调用 findByUserName 方法时,一切正常。
用户 Controller
@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);=
...
}
}
创建 Controller 后,我需要使用 Spring Security 来保护 Controller 的路径,因此我在 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 路径发布请求时,当我尝试通过调用 findByUserName 方法通过 userRepository 实例加载数据时,我会在 CustomAuthenticationProvider 类中收到 NullPointerException,因为 userRepository 实例为 null。
自定义身份验证提供程序
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 能够在我的 Controller 和同一应用程序中使用 Bean Autowiring 实例,但在另一个类中却不会 Autowiring 它们?
最佳答案
问题是您像这样 new CustomAuthenticationProvider()
创建您的 CustomAuthenticationProvider
,所以它不是真正的 spring bean,并且它的字段无法注入(inject)。您需要做的是定义 CustomAuthenticationProvider
bean,它将起作用。
关于java - 使用 spring security 时 Spring boot @Autowired 存储库实例为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44841797/