我在包含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");
}
}
答案 0 :(得分:13)
@SpringBootApplication
是@Configuration
,@EnableAutoConfiguration
,@ComponentScan
的简写。这使得Spring可以为此下面的当前包和包执行组件扫描。因此,com.example
和com.example
下的所有课程都会被扫描以创建bean,而com.example
以外的任何其他课程都不会com.securitymodule
因此,要么将@ComponentScan(basePackages = {"com.securitymodule"})
添加到您的主要课程中,要么将WebSecurityConfigurerAdapter
的包裹设为com.example.securitymodule