My situation is this:
我正在构建一个spring启动应用程序,当我在控制器中自动装载UserRepository时,它初始化它,当我尝试调用findByUserName方法时,一切正常 .
UserController
@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类中添加了以下配置:
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 .
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());
...
}
My questions are this:
在应用程序运行期间,bean的状态是否相同?应用程序加载时是否创建了bean?
Why Spring Boot manages to autowire the instance with the bean in my controller and in the same application but in another class it does not autowire them?
1 回答
问题是你创建了像
new CustomAuthenticationProvider()
这样的CustomAuthenticationProvider
,因此无法注入's not really a spring bean and it'的字段 . 你需要做的是定义CustomAuthenticationProvider
bean,它会起作用 .