WebSecurityConfigurerAdapter除了包含的类的软件包以外,我在其他软件包中具有extendend @SpringBootApplication。然后,它无法生成其默认的用户名和密码。
WebSecurityConfigurerAdapter
@SpringBootApplication
当它在同一包中时,它工作正常。
package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
扩展 WebSecurityConfigurerAdapter的* 类 *
package com.securitymodule; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration @EnableWebSecurity public class WebSecurity extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // TODO Auto-generated method stub super.configure(http); http.antMatcher("/**").authorizeRequests().anyRequest().hasRole("USER").and().formLogin(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // TODO Auto-generated method stub super.configure(auth); auth. inMemoryAuthentication() .withUser("user").password("password").roles("USER"); } }
@SpringBootApplication为短手@Configuration,@EnableAutoConfiguration,@ComponentScan。这使得Spring可以为当前的软件包以及低于此级别的软件包做组件扫描。因此,在所有类com.example和下com.example被扫描bean创建的,而不是任何其他上述com.example像com.securitymodule
@Configuration
@EnableAutoConfiguration
@ComponentScan
com.example
com.securitymodule
因此,要么添加@ComponentScan(basePackages = {"com.securitymodule"})到您的主类中,要么将其打包WebSecurityConfigurerAdapter为com.example.securitymodule
@ComponentScan(basePackages = {"com.securitymodule"})
com.example.securitymodule