Spring Boot 2.0.0中无法自动注入AuthenticationManager问题求助
Hey there! I’ve hit this exact snag when upgrading from Spring Boot 1.5 to 2.x, so I know how confusing it can be. Let’s break down what changed and how to fix the missing AuthenticationManager injection issue.
Why This Happens in Spring Boot 2.0.0
In Spring Boot 1.5.x, the auto-configuration logic automatically exposed an AuthenticationManager bean, which is why your @Autowired worked out of the box. But in Spring Boot 2.x, this behavior changed: the default setup no longer registers AuthenticationManager as a globally accessible bean. That’s why your injection fails after the upgrade.
The Fix: Expose AuthenticationManager Manually
You need to explicitly expose the AuthenticationManager as a bean in your web security configuration. Here’s how to do it:
Update your Web Security Config
ExtendWebSecurityConfigurerAdapterand override theauthenticationManagerBean()method, adding the@Beanannotation to make it injectable:@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // Optional: Define your UserDetailsService and PasswordEncoder here @Autowired private UserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } // This is the key step to expose AuthenticationManager as a bean @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }Inject It in Your Authorization Server Config
Now you can safely@AutowiredtheAuthenticationManagerinto yourAuthorizationServerConfigurerAdapterimplementation:@Configuration @EnableAuthorizationServer public class AuthServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private PasswordEncoder passwordEncoder; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("client-id") .secret(passwordEncoder.encode("client-secret")) .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); // Add other configurations like token store, access token converter here } }
A Quick Note on Spring Boot 2.x OAuth2 Changes
Keep in mind that Spring Boot 2.x also deprecated some older OAuth2 auto-configuration classes. If you run into additional issues, make sure you’re using the correct dependencies (like spring-security-oauth2-autoconfigure) and align your setup with the latest Spring Security OAuth2 practices.
内容的提问来源于stack exchange,提问作者Zohaib Khan

