khateeb
khateeb

Reputation: 5469

Spring Security Filter showing not found despite being defined in Java config

I have configured my Spring application using Java based config. When I start my application, I get the error NoSuchBeanDefinitionException: No bean named 'springSecurityFilterChain' is defined. I have defined all the configuration classes but this error still occurs. How do I fix this?

My main class:

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 class is:

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer { }

My MVC Config class is:

@Configuration
@EnableWebMvc
@ComponentScan
@Import(SecurityConfig.class)
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/").setCachePeriod(31556926);
    }
}

My Security Config class is:

@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();
    }
}

Upvotes: 1

Views: 1728

Answers (1)

NikolaB
NikolaB

Reputation: 4936

Try replacing this line:

dispatcherContext.register(MvcConfig.class);    

with:

dispatcherContext.setConfigLocation("your.config.package");

add line below:

container.addListener(new ContextLoaderListener(dispatcherContext));

There is no need to @Import(SecurityConfig) since setConfigLocation will automatically detect all @Configuration annotated classes.

Upvotes: 1

Related Questions