我使用基于Java的配置配置了我的Spring应用程序。当我启动我的应用程序时,我收到错误NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined
。我已经定义了所有配置类,但仍然会出现此错误。我该如何解决这个问题?
我的主要课程:
public class SiteMain implements WebApplicationInitializer {
private void initSpringMvcServlet(ServletContext container) {
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.register(MvcConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
private void initSpringRootContext(ServletContext container) {
XmlWebApplicationContext rootContext = new XmlWebApplicationContext();
rootContext.setConfigLocation("/WEB-INF/site.xml");
container.addListener(new ContextLoaderListener(rootContext));
}
@Override
public void onStartup(ServletContext container) throws ServletException {
initSpringRootContext(container);
initSpringMvcServlet(container);
}
}
My Security Initializer类是:
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }
我的MVC配置类是:
@Configuration
@EnableWebMvc
@ComponentScan
@Import(SecurityConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
}
}
我的安全配置类是:
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**").permitAll().anyRequest().authenticated()
.and().formLogin().loginPage("/").permitAll()
.and().logout().permitAll()
.and().rememberMe();
}
}
答案 0 :(得分:1)
尝试替换此行:
dispatcherContext.register(MvcConfig.class);
使用:
dispatcherContext.setConfigLocation("your.config.package");
在下面添加一行:
container.addListener(new ContextLoaderListener(dispatcherContext));
不需要@Import(SecurityConfig),因为setConfigLocation
会自动检测所有@Configuration带注释的类。