在spring中可以通过代码的方式配置原来的xml文件.在用java 代码配置web.xml时候,spring文档说配置类要实现WebApplicationInitializer接口.关于为什么要实现org.springframework.web.WebApplicationInitializer接口,记录下.
其实是对servlet规范的一种使用.servlet早就支持用代码实现相关的xml配置.
servlet相关接口:
@HandlesTypes:
解释:实现了ServletContainerInitializer 接口的类在web程序启动的时候会被容器扫描加载并且调用其onStartup方法(在方法中注册servlet或者filters等web.xml中会进行的配置).但是实现此接口的类必须在某个jar包中的META-INF/services路径下进行声明(java spi).spring 中的实现类为org.springframework.web.SpringServletContainerInitializer,该类在springweb jar包中声明:
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();
if (webAppInitializerClasses != null) {
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer) waiClass.newInstance());
}
catch (Throwable ex) {
throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
}
}
}
}
if (initializers.isEmpty()) {
servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
return;
}
servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
}
SpringServletContainerInitializer上的注解:@HandlesTypes(WebApplicationInitializer.class)
意思是向该类注入HandlesTypes指定的类或者实现该接口的类.所以我们一般实现WebApplicationInitializer,通过代码注册servlet就可以使用了.
所以流程是spring 中的SpringServletContainerInitializer onStartup()方法被容器调用,然后onStartup()方法最终调用的是我们实现类中的方法.
参考servlet3.1规范
spring-framework-reference
--
增加篇文章:http://stefan-isele.logdown.com/posts/201646 (2017年11月10日10:35:44)
来源:oschina
链接:https://my.oschina.net/u/857820/blog/527793