spring对servlet3.0的支持
java 注解的出现可以说对java编程影具有深远的影响。servlet也不例外,
servlet3.0
可以使开发人员通过java config 的方式轻松的摆脱 web.xml。spring boot应该是比较好的证明方式
ServletContainerInitializer
servlet3.0
提供了这个接口,当然servlet 容器也做了相应的扩展 如tomcat7
spring 对此接口也做了好的适配
WebApplicationInitializer
应该算是对ServletContainerInitializer
最底层的接口了 它里面只有一个onStartup(ServletContext servletContext)
方法,当然实现类AbstractDispatcherServletInitializer AbstractAnnotationConfigDispatcherServletInitializer
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
throws ServletException {
List<WebApplicationInitializer> initializers = new LinkedList<>();
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)
ReflectionUtils.accessibleConstructor(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);
}
}
}
我们可以看到这个类是 ServletContainerInitializer扩展,我们点开它的jar包可以看到 META-INF/services/javax.servlet.ServletContainerInitializer
这个就是对SPI 的机制对ServletContainerInitializer的实现 我们看到SpringServletContainerInitializer这个类上的签名@HandlesTypes(WebApplicationInitializer.class)
onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) webAppInitializerClasses就是WebApplicationInitializer.class类型。看有看出来spring的思路。
因此我们可以通过扩展
AbstractAnnotationConfigDispatcherServletInitializer
实现五无web.xml
@Configurable
public class MvcConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringContextConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
@Configurable
@ComponentScan(basePackages = "com.sunjin.vip",
excludeFilters = {
@ComponentScan.Filter()
})
public class SpringContextConfig {
}
@Configurable
@ComponentScan(basePackages = "com.sunjin.vip.controller")
@EnableWebMvc
public class SpringMvcConfig{
}
这样就看大没有web.xml我们也可以部署一个web项目
结束语
:spring 应该是目前使用最广的 java框架了 spring 的生态和它的编程思想赢响了一代又一代程序猿。