1. 程式人生 > >Servlet3.0下基於註解的SpringMVC3.1配置

Servlet3.0下基於註解的SpringMVC3.1配置

Spring3.1.x系列的一個新特性就是支援了Servlet3.0規範,基於註解的方式配置SpringMVC框架。官方文件描述如下:

3.1.10 Support for Servlet 3 code-based configuration of Servlet Container

The new WebApplicationInitializer builds atop Servlet 3.0's ServletContainerInitializer support to provide a programmatic alternative to the traditional web.xml.

  • See org.springframework.web.WebApplicationInitializer Javadoc

既然如此,我們就來實現一下。根據WebApplicationInitializer 的註釋說明,實現該介面即可。

/**
 * 基於Servlet3.0的,相當於以前<b>web.xml</b>配置檔案的配置類
 * 
 * @author OneCoder
 * @Blog http://www.coderli.com
 * @date 2012-9-30 下午1:16:59
 */
public
class DefaultWebApplicationInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext appContext) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(DefaultAppConfig
.class); appContext.addListener(new ContextLoaderListener(rootContext)); ServletRegistration.Dynamic dispatcher = appContext.addServlet( "dispatcher", new DispatcherServlet(rootContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/"); } }

這裡說明一下,根據WebApplicationInitializer 類的註釋說明(OneCoder建議大家多閱讀程式碼註釋(Javadoc),其實也就是API文件。),其實這裡有兩種初始化rootContext的方式。一種是利用XmlWebApplicationContext,即Spring的配置是通過傳統的Xml的方式配置的。另一種就是這裡用到的AnnotationConfigWebApplicationContext ,即Spring的配置也是通過註解的方式。這裡,我們既然說了是完全零配置檔案,那麼我就採用第二種方式。利用新建的配置類,配置註解的方式,完成配置。

/**
 * Spring3.1基於註解的配置類, 用於代替原來的<b>applicationContext.xml</b>配置檔案
 * 
 * @author lihzh
 * @date 2012-10-12 下午4:23:13
 */
@Configuration
@ComponentScan(basePackages = "com.coderli.shurnim.*.biz")
public class DefaultAppConfig {

}

可以看到,基本原有在配置檔案裡的配置,這裡都提供的相應的註解與之對應。這裡我們僅僅配置的包掃描的根路徑,用於SpringMVC配置的掃描,以進一步達到零配置檔案的效果。在業務包下,寫一個MVC的controller類:

/**
 * 使用者操作Action類
 * 
 * @author lihzh
 * @date 2012-10-12 下午4:12:54
 */
@Controller
public class UserAction {

	@RequestMapping("/user.do")
	public void test(HttpServletResponse response) throws IOException {
		response.getWriter().write("Hi, u guy.");
	}
}
怎麼樣,OK了吧。看看我們的工程,這回是不是真的一個配置檔案都沒有。 寫在最後,OneCoder這裡只是零配置檔案的配置方式,不參與討論配置檔案與註解的優劣問題的爭執。我覺得,這就是個人喜好問題。任何東西,有好的一面就有不利的一面,堅持你喜歡的並承擔相應後果就好:)