[英]How to configure Spring Security with already existing WebApplicationInitializer?
I am doing a web site project with Spring/ Spring MVC I learned how to configure a spring with the java classes and annotations approach, which by far is better than the XML. 我正在使用Spring / Spring MVC做一个网站项目,我学会了如何使用java类和注释方法配置spring,到目前为止,它比XML更好。
Now I want to use Spring Security with my application. 现在,我想在应用程序中使用Spring Security。 However I could not understand how to configure it with already existing
WebApplicationInitializer
? 但是我不明白如何使用现有的
WebApplicationInitializer
对其进行配置?
The Spring documentation is not so clear. Spring文档不是很清楚。
Here is my code and what I have so far: 这是我的代码以及到目前为止的内容:
public class AppInitializer implements WebApplicationInitializer{
//public class AppInitializer {
private static final Class<?>[] CONFIG_CLASSES = new Class<?>[]{SiteConfigs.class, AdminConfigurations.class};
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(CONFIG_CLASSES);
DispatcherServlet servlet = new DispatcherServlet(appContext);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", servlet);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
If I add AbstractSecurityWebApplicationInitializer
to the classpath the container throws exception. 如果我将
AbstractSecurityWebApplicationInitializer
添加到类路径,则容器将引发异常。
HTTP Status 500 - No WebApplicationContext found: no ContextLoaderListener registered?
So how to config Spring Security so that springSecurityFilterChain
get initialized 那么如何配置Spring Security以使
springSecurityFilterChain
初始化
The exception tells you that you don't have a ContextLoaderListener
which, in your case, is true. 异常告诉您,没有
ContextLoaderListener
(对于您而言)为true。 You only have a DispatcherServlet
. 您只有一个
DispatcherServlet
。 By default Spring Security will only lookup the filters from the root application context (the one loaded by the ContextLoaderListener
). 默认情况下,Spring Security只会从根应用程序上下文(由
ContextLoaderListener
加载的那个)中查找过滤器。
If you want to let it use a DispatcherServlet
s context instead you have to tell it that. 如果要让它使用
DispatcherServlet
的上下文,则必须告诉它。 You can tell it which to use by overriding the getDispatcherWebApplicationContextSuffix()
method. 您可以通过重写
getDispatcherWebApplicationContextSuffix()
方法来告诉它使用哪个。
You aren't limited to a single WebApplicationInitializer
you can have multiple in general you want to have one for your application bootstrapping and another to add security. 您不仅限于一个
WebApplicationInitializer
,通常可以有多个WebApplicationInitializer
,一个应用程序用于引导,另一个用于增加安全性。 You can then leverage the Spring convenience classes to save a couple of lines of code. 然后,您可以利用Spring便利类保存几行代码。 See the Spring Security Reference for a sample.
有关示例,请参见Spring Security Reference 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.