实现WebApplicationinitializer
的类都可以在web应用程序启动时被加载。
这个是通过SpringServletContainerIntializer
实现ServletContainerIntializer
实现的。
首先建个WebApplicationInitializer.java
package com.boventech.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* WebApplicationInitializer接口
* @author hu.sun
*/
public interface WebApplicationInitializer{
public void config(ServletContext context) throws ServletException;
}
继续,由于必须通过SpringServletContailnerIntializer
才能加载,再建个SpringServletContailnerIntializer
类:
package com.boventech.config;
import java.lang.reflect.Modifier;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.HandlesTypes;
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer{
@Override
public void onStartup(Set<Class<?>> webApplicationInitializers, ServletContext servletContext)
throws ServletException {
if (webApplicationInitializers != null) {
for (Class<?> webApplicationInitializerClass : webApplicationInitializers) {
if (!webApplicationInitializerClass.isInterface() && !Modifier.isAbstract(webApplicationInitializerClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(webApplicationInitializerClass)) {
try {
((WebApplicationInitializer) webApplicationInitializerClass.newInstance()).config(servletContext);
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate webApplicationInitializer class", ex);
}
}
}
}
}
}
注意:
要实现ServletContainerInitializer
接口,必须指定实现的类。@HandlesTypes
就起到关键性作用。
还有一个最重要的:在Libraries->Spring -web-x.x.x.jar->META-INF/services/javax.servlet.ServletContainerInitializer
里面的内容必须是实现ServletContainerInitializer
的类,即com.boventech.config.SpringServletContainerInitializer
。
package com.boventech.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.util.WebAppRootListener;
public class DefaultServletConfig implements WebApplicationInitializer{
@Override
public void config(ServletContext servletContext) throws ServletException{
servletContext.addListener(new ContextLoaderListener());
servletContext.addListener(new WebAppRootListener());
servletContext.setInitParameter("contextConfigLocation", "classpath*:**/*Context.xml");
//设置webAppRootKey得值以得到根目录
servletContext.setInitParameter("webAppRootKey", "learning");
}
}
网友评论