Spring MVC full Annotation configuration-no web. xml

Source: Internet
Author: User

After Serlvet 3, we can use annotations to configure the Servlet, which is a good fit for a framework such as Spring . Spring also adds a lot of new features to this feature. This article will simply convert the previous XML configuration to the configuration of Java code. Code configuration makes programmers feel more process-like, unlike configuring many code programmers who are reluctant to look into.


Next, replace the configuration of our previous Web. Xml and spring-mvc.xml . That is, you do not see these two configuration files in your Web project. (There may be children's shoes will say that this configuration may not be convenient for future modifications, can not achieve only modify the configuration file to switch some environments.) In fact, the 0 configuration file simply modifies the configuration of the class definition and does not modify the flexibility of the previous configuration file. I think no one will change the configuration of a servlet in the previous Web. Xml . Moreover, these so-called configuration file flexibility, only for a certain value, we can write in our properties file, and spring for such configuration files have very good support, and the use of very convenient, interested children shoes can go to search. So please dispel the idea that the configuration is not flexible).


To get to the point, first we have to replace Web. Xml. Configure Dispatchservlet in spring MVC, which is the core class of spring MVC (the specific role of this class is referenced in the spring MVC-related documentation). That is, the class is initialized when the container is started, and the corresponding parameters are configured.

The configuration for Dispatchservlet in our web. XML is as follows:

<servlet> <servlet-name>dispatcher</servlet-name> <servlet-class> Org.springframework.web . servlet. Dispatcherservlet </servlet-class> <init-param> <param-name>contextconfiglocation</param-nam e> <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value> </init-param> <load-o N-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>dispatcher </servlet-name> <url-pattern>/</url-pattern></servlet-mapping>


After Servlet3, to support dynamic add servlet configuration, refer to the servletcontext.addservlet method. So we can use the Abstractdispatcherservletinitializer class provided by spring MVC. The class is the class relationship Abstractdispatcherservletinitializer-Webapplicationinitializer, ( Click to view Webapplicationinitializer) in Abstractdispatcherservletinitializer to override the Onstartup method, call the Servletcontext.addservlet to implement registering the servlet. By looking at the abstractdispatcherservletinitializer source code, we found that only three ways of rewriting his Dispatchservlet can be completed. For details, see the sample code:

public class webinitialconfiguration extendsabstractdispatcherservletinitializer {@ Overrideprotected webapplicationcontext createservletapplicationcontext ()  { Annotationconfigwebapplicationcontext context = new annotationconfigwebapplicationcontext ( );// scan the class under the demo.config package with @ configuration annotation // you can add it by manually such  As:// context.register (class<?>... annotatedclasses)  -> context.register ( WEBMVCCONFIGURATION.CLASS,&NBSP;APPCONFIG.CLASS,&NBSP, ...)  This configuration like:// <init-param>    // < param-name>contextconfiglocation</param-name>    // <param-value>/ Web-inf/spring/dispatcher-config.xml</param-value>    // </init-param>     // all the configuration classes are in the same  Package, so use the getclass ()  method to get the package.  Here the package name is com.sample.configcontext.scan (ClassUtils.getPackageName ( GetClass ())); return context;} @Overrideprotected  string[] getservletmappings ()  {// Set the URL  mappingreturn new string[] {  "/" &NBSP;};} @Overrideprotected  webapplicationcontext createrootapplicationcontext ()  {return null;}}


Careful children's shoes can look at the source of Abstractdispatcherservletinitializer, you will find in the code called the Contextservlet.addservlet method:

Dispatcherservlet Dispatcherservlet = new Dispatcherservlet (servletappcontext); Servletregistration.dynamic registration = Servletcontext.addservlet (Servletname, DispatcherServlet);


When we start the Servlet3 container (this article uses TOMCAT7), you will see the following startup information:

Info:initializing Spring frameworkservlet ' dispatcher ' info:frameworkservlet ' dispatcher ': initialization startedmapped URL Path [/**] onto handler of type [class Org.springframework.web.servlet.resource.defaultservlethttprequesthandler]info:frameworkservlet ' Dispatcher ': Initialization completed in 843 MS



Next, replace the Spring-mvc.xml, in which we can use the interface provided by spring to complete the configuration of all controller registrations and view resolution in just a few parts of the configuration.

The XML configuration is as follows:

<context:component-scan base-package= "Com.sample.controller"/><context:annotation-config/><!-- This tag registers the defaultannotationhandlermapping and annotationmethodhandleradapter beans that is required For Spring MVC--><mvc:annotation-driven/><bean class= " Org.springframework.web.servlet.view.InternalResourceViewResolver "> <propertyname=" prefix "value="/web-inf /pages/"/> <propertyname=" suffix "value=". jsp "/></bean> <!--this tag allows for mapping the Dispatch Erservlet to "/"--><mvc:default-servlet-handler/>


First, in spring MVC, we can use @configuration for spring configuration, and we just need to scan this class of configuration classes. The next step is to start the specific configuration of spring MVC. Using @enablewebmvc, this annotation is equivalent to <mvc:annotation-driven/>, and the label's specific meaning is explained in the XML configuration.


Next we're going to scan our controller, which has the @controller class. So we use @componentscan for scanning, which is equivalent to <context:componet-scan>.


Spring MVC requires a definition of the view's parsing, so we need to instantiate a resourceviewresolver in that class, which is defined depending on the needs.


The specific code is as follows:


@Configuration//<mvc:annotation-driven/> @EnableWebMvc @componentscan (basepackages={"Com.sample.controller "}) public class Webmvcconfiguration extends Webmvcconfigureradapter {//equals: <mvc:default-servlet-handler/>@ overridepublic void configuredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable ();} Add the Resolver@beanpublic internalresourceviewresolver internalresourceviewresolver () { Internalresourceviewresolver resolver = new Internalresourceviewresolver (); Resolver.setprefix ("/web-inf/pages/"); Resolver.setsuffix (". jsp"); return resolver;}}


At this point we add our controller to the Com.sample.controller package, then define our requestmapping and start the server again, and you will see an increase in the previously detected controller information.

Info:mapped "{[/test],methods=[get],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public Java.lang.String Com.sample.controller.TestController.test ()


At this point, a simple replacement has been completed, and more features will continue to be added in subsequent articles, such as: Spring-security, Thymeleaf (a very nice view frame).

This article is from the "Sg-yyz" blog, make sure to keep this source http://sgyyz.blog.51cto.com/5069360/1575102

Spring MVC full Annotation configuration-no web. xml

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.