"Spring Boot" (13), Spring boot automatic configuration Springmvc

Source: Internet
Author: User
Tags locale static class
1, SPRINGMVC automatic configuration of official documents

Spring Boot Official Documentation: SPRINGMVC configuration document in spring boot


2. Spring MVC auto-configuration

Spring Boot provides automatic configuration items that are commonly used by most SPRINGMVC applications.

The following is the default configuration of Spring boot for SPRINGMVC (from the official website, self translation): contentnegotiatingviewresolver and Beannameviewresolver are automatically configured of beans.

adds a view parser to the container customization, and the Contentnegotiatingviewresolver bean is automatically combined.

Automatically configured Viewresolver:contentnegotiatingviewresolver is a combination of all the view parsers

public class Webmvcautoconfiguration {
    //other code ...
    
    @Bean
    @ConditionalOnBean (viewresolver.class)
    @ConditionalOnMissingBean (name = "Viewresolver", value = Contentnegotiatingviewresolver.class) Public
    contentnegotiatingviewresolver Viewresolver (BeanFactory Beanfactory) {
        Contentnegotiatingviewresolver resolver = new Contentnegotiatingviewresolver ();
        Resolver.setcontentnegotiationmanager (
            Beanfactory.getbean (Contentnegotiationmanager.class));
        Contentnegotiatingviewresolver uses all of the other view resolvers to locate
        //A view so it should have a high prece Dence
        Resolver.setorder (ordered.highest_precedence);
        Return resolver
    }
}

which Contentnegotiatintviewresolver class implements Viewresoler Interface:

public class Contentnegotiatingviewresolver extends Webapplicationobjectsupport implements Viewresolver, Ordered, Initializingbean {//other code ... @Override public View resolveviewname (String viewName, Locale Locale) throws Excep
		tion {requestattributes attrs = requestcontextholder.getrequestattributes ();
		Assert.state (attrs instanceof servletrequestattributes, "No current Servletrequestattributes");
		Get all the mediatype, such as application/json,text/html, etc...
		list<mediatype> requestedmediatypes = GetMediaTypes (((servletrequestattributes) attrs). GetRequest ()); if (requestedmediatypes!= null) {//Get all views list<view> candidateviews = getcandidateviews (viewName, Locale, R
			Equestedmediatypes);
			Get the most appropriate view on request Bestview = Getbestview (Candidateviews, Requestedmediatypes, attrs);
			if (Bestview!= null) {return bestview;
	
	}//other code ...} Private list<view> getcandidateviews (String viewName, Locale Locale, list<mediatype> requEstedmediatypes) throws Exception {list<view> candidateviews = new arraylist<view> ();
			for (Viewresolver viewResolver:this.viewResolvers) {View view = Viewresolver.resolveviewname (viewName, locale);
			if (view!= null) {Candidateviews.add (view); for (mediatype requestedmediatype:requestedmediatypes) {list<string> extensions = This.contentnegotiatio
				Nmanager.resolvefileextensions (Requestedmediatype);
					for (string extension:extensions) {string viewnamewithextension = ViewName + '. ' + extension;
					View = Viewresolver.resolveviewname (viewnamewithextension, locale);
					if (view!= null) {Candidateviews.add (view);
	}}}//other code ... return candidateviews; }
}
support for static resource folders and Webjars static home page access. Custom Favicon icon Automatic registration of Converter, Genericconverter, Formatter Beans.

Converter: Converters, for type conversions

Formatter: Formatter

@Bean
//If Spring.mvc.date-format is configured, automatically registers the formatter<date> Bean
@ConditionalOnProperty (prefix = " Spring.mvc ", name =" Date-format ") public
formatter<date> Dateformatter () {return
    new Dateformatter ( This.mvcProperties.getDateFormat ());
}

A formatted converter that is automatically added, just add it to the container. supports httpmessageconverters message converters.

httpmessageconverter: Springmvc used to convert HTTP requests and responses.

httpmessageconverters is all httpmessageconverterobtained from the container, and if you need to add httpmessageconverter to the container, You only need to register your custom components in the container. automatic configuration messagecodesresolver is used for generating rules for error codes.

Prefix_error_code:error_code + "." + Object name + "." + Field

Postfix_error_code:object name + "." + Field + "." + error_code automatically use Configurablewebbindinginitializerbean.

You can customize the configuration of a configurablewebbindinginitializer to replace the default and need to be added to the container.

Initialize webdatabinder: Used to bind the request data to the data model, and so on.

Package Org.springframework.boot.autoconfigure.web is a web of all automatic configuration scenarios.

From the official website:

If you are want to keep Spring Boot MVC features, and your just want to add additional MVC configuration (interceptors, Formatt ERS, view controllers etc.) You can add your own @Configuration class of type webmvcconfigureradapter, but without @EnableWebMvc. If you are wish to provide custom instances of requestmappinghandlermapping, requestmappinghandleradapter or ExceptionHandler Exceptionresolver you can declare a Webmvcregistrationsadapter instance providing such.

If you are want to take complete control of the Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.
3. Extended SPRINGMVC

Write a configuration class that is a subclass of the Webmvcconfigureradapter class, but cannot annotate @enablewebmvc annotations.

This preserves all of the autoconfiguration and can also use a custom extended configuration.

Webmvcconfigureradapter can be used to extend the functionality of SPRINGMVC
@Configuration public
class Mymvcconfig extends webmvcconfigureradapter{

	@Override public
	void Addviewcontrollers (Viewcontrollerregistry registry) {
/ /		Super.addviewcontrollers (registry);
        The browser sends the/CAY request and jumps directly to the success page.
		Registry.addviewcontroller ("/cay"). Setviewname ("Success");
	}

Principle: 1, webmvcautoconfiguration is SPRINGMVC automatic configuration class, in the internal maintenance of an internal class webmvcautoconfigurationadapter, The class inherits from the Webmvcconfigureradapter and looks at the definition:

@Configuration
@Import (enablewebmvcconfiguration.class)
@EnableConfigurationProperties ({ Webmvcproperties.class, Resourceproperties.class}) public
static class Webmvcautoconfigurationadapter extends Webmvcconfigureradapter {}

and Webmvcconfigureradapter also implements the Webmvcconfigurer interface:

Public abstract class Webmvcconfigureradapter implements Webmvcconfigurer {}
So the custom configuration class (this example is Mymvcconfig) is a WebmvcconfigurerThe implementation class for the interface.


2, in doing webmvcautoconfigurationadapter automatic configuration will import @Import (enablewebmvcconfiguration.class)

@Configuration public
Static class Enablewebmvcconfiguration extends Delegatingwebmvcconfiguration {}

Parent class:

@Configuration public
class Delegatingwebmvcconfiguration extends Webmvcconfigurationsupport {

	private final Webmvcconfigurercomposite configurers = new Webmvcconfigurercomposite ();

	Gets all webmvcconfigurer
	@Autowired (required = false) public void setconfigurers from the container
	(list< Webmvcconfigurer> configurers) {
		if (! Collectionutils.isempty (configurers)) {
			this.configurers.addWebMvcConfigurers (configurers);}}}
   3), all the webmvcconfigurer in the container will work together.
class Webmvcconfigurercomposite implements Webmvcconfigurer {private final list<

	webmvcconfigurer> delegates = new arraylist<webmvcconfigurer> (); public void Addwebmvcconfigurers (list<webmvcconfigurer> configurers) {if (!
		Collectionutils.isempty (configurers)) {this.delegates.addAll (configurers); @Override public void Addformatters (Formatterregistry registry) {for (Webmvcconfigurer DELEGATE:THIS.D
		Elegates) {delegate.addformatters (registry); @Override public void Addinterceptors (Interceptorregistry registry) {for (Webmvcconfigurer Delegate:this.dele
		Gates) {delegate.addinterceptors (registry); @Override public void Addviewcontrollers (Viewcontrollerregistry registry) {for (Webmvcconfigurer Delegat
		E:this.delegates) {delegate.addviewcontrollers (registry); }//other code ...} 

As you can see from the source, all webmvcconfigurer objects obtained from the container will be called to the corresponding configuration method.
4, and finally the 2nd and 3rd can be seen, the custom configuration class will also be called.
Summary: SPRINGMVC's automatic configuration and custom extended configuration all work.

4, fully take over the SPRINGMVC

@EnableWebMvc Annotations are used on the configuration class so that the automatic configuration of spring boot to SPRINGMVC is invalidated, and all require a custom configuration.

Principle: Why the automatic configuration is invalid after using the @EnableWebMvc ?

1), the definition of ENABLEWEBMVC annotation

@Import (delegatingwebmvcconfiguration.class) public
@interface Enablewebmvc {}

2), imported the Delegatingwebmvcconfiguration component configuration

@Configuration public
class Delegatingwebmvcconfiguration extends Webmvcconfigurationsupport {}

3), view the signature of the Webmvcautoconfiguration automatic configuration class

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass ({servlet.class, Dispatcherservlet.class ,
		Webmvcconfigureradapter.class})
///If the component is not in the container, this automatic configuration class automatically takes effect.
@ConditionalOnMissingBean (Webmvcconfigurationsupport.class)
@AutoConfigureOrder (ordered.highest_ Precedence +)
@AutoConfigureAfter ({dispatcherservletautoconfiguration.class,
		Validationautoconfiguration.class}) Public
class Webmvcautoconfiguration {}

4), @EnableWebMvc Import the Webmvcconfigurationsupport component in, causing spring boot to fail the automatic configuration of SPRINGMVC. That is, the Webmvcautoonfiguration configuration class was not registered successfully.


5, modify the default configuration of Springboot

mode:

1. Spring boot automatically configures a number of components in a container that first checks for a user-defined bean or component. If it does, it uses user-defined, and if not, spring boot is automatically configured, and if some components can have multiple, the user can customize the Add component and join the container so that spring boot automatically combines the user's configured and default combinations.

2, there will be a lot of configurer in spring boot to help users to extend the configuration.


==================== to advertise, welcome attention ====================

Qq:
412425870</

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.