博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Web工程web.xml零配置即使用Java Config + Annotation
阅读量:5821 次
发布时间:2019-06-18

本文共 9665 字,大约阅读时间需要 32 分钟。

  hot3.png

在开始之前,我们需要注意一下,要基于Java Config实现无web.xml的配置,我们的工程的Servlet必须是3.0及其以上的版本;

1、我们要实现无web.xml的配置,只需要关注实现WebApplicationInitializer这个接口,以下为Spring源码:

public interface WebApplicationInitializer {    /**     * Configure the given {@link ServletContext} with any servlets, filters, listeners     * context-params and attributes necessary for initializing this web application. See     * examples {@linkplain WebApplicationInitializer above}.     * @param servletContext the {@code ServletContext} to initialize     * @throws ServletException if any call against the given {@code ServletContext}     * throws a {@code ServletException}     */    void onStartup(ServletContext servletContext) throws ServletException;}

2、我们这里先不讲他的原理,只要我们工程中实现这个接口的类,Spring容器在启动时候就会监听到我们所实现的这个类,从而读取我们的

配置,就如读取web.xml一样,我们的实现类如下所示:

public class WebProjectConfigInitializer implements WebApplicationInitializer {	@Override	public void onStartup(ServletContext container) {		initializeSpringConfig(container);		initializeLog4jConfig(container);		initializeSpringMVCConfig(container);		registerServlet(container);		registerListener(container);		registerFilter(container);	}	private void initializeSpringConfig(ServletContext container) {		// Create the 'root' Spring application context		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();		rootContext.register(AppConfiguration.class);		// Manage the life cycle of the root application context		container.addListener(new ContextLoaderListener(rootContext));	}	private void initializeSpringMVCConfig(ServletContext container) {		// Create the spring rest servlet's Spring application context		AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();		dispatcherContext.register(RestServiceConfiguration.class);		// Register and map the spring rest servlet		ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",				new DispatcherServlet(dispatcherContext));		dispatcher.setLoadOnStartup(2);		dispatcher.setAsyncSupported(true);		dispatcher.addMapping("/springmvc/*");	}	private void initializeLog4jConfig(ServletContext container) {		// Log4jConfigListener		container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");		container.addListener(Log4jConfigListener.class);		PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);	}	private void registerServlet(ServletContext container) {		initializeStaggingServlet(container);	}	private void registerFilter(ServletContext container) {		initializeSAMLFilter(container);	}	private void registerListener(ServletContext container) {		container.addListener(RequestContextListener.class);	}	private void initializeSAMLFilter(ServletContext container) {		FilterRegistration.Dynamic filterRegistration = container.addFilter("SAMLFilter", DelegatingFilterProxy.class);		filterRegistration.addMappingForUrlPatterns(null, false, "/*");		filterRegistration.setAsyncSupported(true);	}	private void initializeStaggingServlet(ServletContext container) {		StaggingServlet staggingServlet = new StaggingServlet();		ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);		dynamic.setLoadOnStartup(3);		dynamic.addMapping("*.stagging");	}}

3、以上的Java Config等同于如下web.xml配置:

contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
contextConfigLocation
com.g360.configuration.AppConfiguration
org.springframework.web.context.ContextLoaderListener
log4jConfigLocation
file:${rdm.home}/log4j.properties
org.springframework.web.util.Log4jConfigListener
staggingServlet
staggingServlet
staggingServlet
com.g360.bean.interfaces.StaggingServlet
staggingServlet
*.stagging
SpringMvc
org.springframework.web.servlet.DispatcherServlet
contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
contextConfigLocation
com.g360.configuration.RestServiceConfiguration
1
true
SpringMvc
/springmvc/*
SAMLFilter
org.springframework.web.filter.DelegatingFilterProxy
true
SAMLFilter
/*
org.springframework.web.context.request.RequestContextListener
login.jsp

4、我们分类解读,在web.xml配置里面我们配置的Web Application Context

contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
contextConfigLocation
com.g360.configuration.AppConfiguration
org.springframework.web.context.ContextLoaderListener

就等价于Java Config中的

private void initializeSpringConfig(ServletContext container) {		// Create the 'root' Spring application context		AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();		rootContext.register(AppConfiguration.class);		// Manage the life cycle of the root application context		container.addListener(new ContextLoaderListener(rootContext));	}

 

如此推断,在web.xml配置里面我们配置的log4j

log4jConfigLocation
file:${rdm.home}/log4j.properties
org.springframework.web.util.Log4jConfigListener

就等价于Java Config的

private void initializeLog4jConfig(ServletContext container) {		// Log4jConfigListener		container.setInitParameter("log4jConfigLocation", "file:${rdm.home}/log4j.properties");		container.addListener(Log4jConfigListener.class);		PropertyConfigurator.configureAndWatch(System.getProperty("rdm.home") + "/log4j.properties", 60);	}

 

类此,在web.xml配置里面我们配置的Spring Web(Spring Restful)

SpringMvc
org.springframework.web.servlet.DispatcherServlet
contextClass
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
contextConfigLocation
com.g360.configuration.RestServiceConfiguration
1
true
SpringMvc
/springmvc/*

就等价于Java Config中的

private void initializeSpringMVCConfig(ServletContext container) {		// Create the spring rest servlet's Spring application context		AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();		dispatcherContext.register(RestServiceConfiguration.class);		// Register and map the spring rest servlet		ServletRegistration.Dynamic dispatcher = container.addServlet("SpringMvc",				new DispatcherServlet(dispatcherContext));		dispatcher.setLoadOnStartup(2);		dispatcher.setAsyncSupported(true);		dispatcher.addMapping("/springmvc/*");	}

 

再此,在web.xml配置里面我们配置的servlet

staggingServlet
staggingServlet
staggingServlet
com.g360.bean.interfaces.StaggingServlet
staggingServlet
*.stagging

就等价于Java Config中的

private void initializeStaggingServlet(ServletContext container) {		StaggingServlet staggingServlet = new StaggingServlet();		ServletRegistration.Dynamic dynamic = container.addServlet("staggingServlet", staggingServlet);		dynamic.setLoadOnStartup(3);		dynamic.addMapping("*.stagging");	}

后面以此类推,在这里不加详述了;

5、如上面所说的,我们对Web 工程的整体配置都依赖于AppConfiguration这个配置类,下面是使用@Configuration 配置类注解的,大家使用过的,以此类推,都比较清楚,

这里就不加赘述了;

@Configuration@EnableTransactionManagement@EnableAsync@EnableAspectJAutoProxy@EnableScheduling@Import({ RestServiceConfiguration.class, BatchConfiguration.class, DatabaseConfiguration.class, ScheduleConfiguration.class})@ComponentScan({ "com.service", "com.dao", "com.other"})public class AppConfiguration{  private Logger logger = LoggerFactory.getLogger(AppConfiguration.class);  /**   *    */  public AppConfiguration ()  {    // TODO Auto-generated constructor stub    logger.info("[Initialize application]");    Locale.setDefault(Locale.US);  }}

还有就是对Spring Web配置的类RestServiceConfiguration ,个人可根据自己的实际项目需求在此配置自己的视图类型以及类型转换等等

@Configuration@EnableWebMvc@EnableAspectJAutoProxy(proxyTargetClass = true)@ComponentScan(basePackages = { "com.bean" })public class RestServiceConfiguration extends WebMvcConfigurationSupport {		@Bean	public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {		RequestMappingHandlerAdapter handlerAdapter = super.requestMappingHandlerAdapter();		return handlerAdapter;	}	@Bean	public LocaleChangeInterceptor localeChangeInterceptor() {		return new LocaleChangeInterceptor();	}	@Bean	public LogAspect logAspect() {		return new LogAspect();	}}

 

至此,我们的 web.xml使用Java Config零配置就完了,如果哪里有不对的地方还请大家留言指教。

转载于:https://my.oschina.net/521cy/blog/702864

你可能感兴趣的文章
安卓中数据库的搭建与使用
查看>>
AT3908 Two Integers
查看>>
渐变色文字
查看>>
C++ 0X 新特性实例(比较常用的) (转)
查看>>
node生成自定义命令(yargs/commander)
查看>>
各种非算法模板
查看>>
node-express项目的搭建并通过mongoose操作MongoDB实现增删改查分页排序(四)
查看>>
PIE.NET-SDK插件式二次开发文档
查看>>
如何创建Servlet
查看>>
.NET 设计规范--.NET约定、惯用法与模式-2.框架设计基础
查看>>
win7 64位+Oracle 11g 64位下使用 PL/SQL Developer 的解决办法
查看>>
BZOJ1997:[HNOI2010]PLANAR——题解
查看>>
BZOJ1014:[JSOI2008]火星人prefix——题解
查看>>
使用Unity3D引擎开发赛车游戏
查看>>
HTML5新手入门指南
查看>>
opennebula 开发记录
查看>>
ubuntu 修改hostname
查看>>
sql 内联,左联,右联,全联
查看>>
C++关于字符串的处理
查看>>
6、Web Service-拦截器
查看>>