Spring Boot Practice Toss (v): Custom configuration, extending the spring MVC configuration and using Fastjson

Source: Internet
Author: User

Daily Golden Sentence

Focus and simplicity has always been one of my secrets. Simplicity can be more difficult than complexity: you have to work hard to clear your mind and make it simple. But in the end it's worth it, because once you do it, you can create miracles. --From jobs


Two days ago a little busy, no continuous update, and then chat today. Old Joe's words in the golden sentence are much better, but how many people can really do? At least personally, I am still far from doing this, just a person in this direction, and strive to be concise and easy to understand, with plain English let people quickly understand the understanding, simple example to get started, so that the use of more people to use the expansion of the actual combat, tossing and remembering is to learn to use a good summary of their own To see the person is also a reference method, I hope you can find their own useful ideas or methods. Today, the main point is, continue to the previous chapter of the configuration, we own how to customize the type of security configuration, and use a common tool Fastjson integration to cut in, although there are custom Jacson and Gson, toss is to toss it, otherwise how can open new ideas.

type-safe configuration

In the previous article, we used to set variables directly in Application.properties, which is a common way in spring, but it's not safe for spring boot, and it's too cumbersome to inject configuration with frequent use of @value. The project is especially troublesome to use, the variables in the real project are not as good as the one or two lines in the demo I demonstrated, many times it will be hundreds of rows in dozens of rows, so Spring boot provides a type-safe configuration method, A type-safe configuration is implemented by associating the properties property with a bean and its attributes through @configurationproperties.

The custom configuration is injected through a service-like approach using

1. Create a bean.

// TestInfoSettings.class@Component@ConfigurationProperties//1        "usetest",        "classpath:config/app.properties")publicclass TestInfoSettings {    private String name;    private String age;    //省略get、set}

1: @ConfigurationProperties load the configuration within the properties file, the prefix property specifies a prefix for the configuration, for example: usetest.*=string. Locations can specify a custom file location and does not specify a default use of application.properties.

2, the new config/app.properties under Src/main/resources.


3. Add an interface call to the controller.

//TestController.class...原有省略@RequestMapping("/showSetting")    publicshowSetting(){        new StringBuffer();        sb.append("setting name is : ").append(testInfoSettings.getName());        sb.append("setting age is : ").append(testInfoSettings.getAge());        sb.append("all is : ").append(testInfoSettings);        return JsonResp.success(sb);    }

4, start, set the data injected into the.

Spring MVC configuration in spring boot

Using spring MVC, it is not customary to suddenly use spring boot, because many of the configurations are gone. Simple is not to say that the configuration is not, but spring boot in some way to help you to quickly complete some of the early work, the previous chapter said, spring One of the main features of boot is the automatic configuration and the conditional annotation @conditional to automatically scan and open the function you configured, the second is the MVC viewresolver, interceptors, static resources, Formatter and converter, Httpmessageconverts, Servlet, Filter, listener, and so on, Spring boot uses a call webmvcautoconfiguration and webmvcproperties files to be automatically configured under the path:

Let's take a look at what's usually automatically configured

static resources that are automatically configured

In the original spring MVC configuration, static resources are usually configured like this.

<mvc:default-servlet-handler /><mvc:resources location="/static/" mapping="/static/**" cache-period="864000" />

In spring boot, the configuration of static resources is defined in method Addresourcehandlers. In fact, is a if-else (interested students to see the source code), summed up contains two categories:

1. Class path File
The static files under the/static,/public,/resources, and/meta-inf/resources folders under the Classpath are mapped directly to/** to provide access.

2, Webjar
Map the static file under the Webjar/meta-inf/resources/webjars to/webjar/**.
What is Webjar? It was someone who helped us encapsulate the common front-end scripting framework in the jar package, and then invoke the script through the jar package, which can be seen in detail on the website: http://www.webjar.org

Finally, if we want to modify the mapping of the static paths and increase the cache time, we only need to modify the Static-path-pattern and Cache-period in the configuration file:


As for the static file storage path, because the general commonly used static files are placed in these directories, basically can meet the requirements, if you want to customize, modify spring.resources.static-locations= can.

automatic configuration of formatter and converter

Searching for formatter, we can find the definition of addformatters in this method, we only need to define the implementation class Bean converter, genericconverter and formatter interface implementation, will register bean to spring Mvc. More simple, no longer cite an example.

Automatic configuration Httpmessageconverters

Similarly, search messageconverters, will find Configuremessageconverters, this method is directly add Httpmessageconverters bean, And this bean is defined in the Httpmessageconvertautoconfiguration class, the source code is as follows:

It is simple to add a defined converter, where the default load is the following eight classes:

There are students to ask Stringhttpmessageconverter why there are two, in fact, only the character set used a UTF-8 and a iso-8859-1. There is also the default Goson, why did you not see it, later in this chapter?

Auto-configured Viewresolver

Similarly, search Viewresolver, will find three: Internalresourceviewresolver, Beannameviewresolver, Contentnegotiatingviewresolver.

"1" contentnegotiatingviewresolver
The special viewresolver provided in Spring MVC, which does not handle the view itself, acts as a proxy for different viewresolver to handle different view. The source code is as follows:

"2" Internalresourceviewresolver
This is the most commonly used parser to get the actual page by setting prefixes, suffixes, and methods in the controller to return a string of view names. The source code is as follows:

It is a configuration file to get the prefix, set the parameters as follows:


"3" Beannameviewresolver
The definition is simple, and the function is to find out if there is a defined bean name in the string that returns the value of the Controller method, and if so, it is rendered with a defined view.

For example: We define a bean called TestView, the return type is Mappingjackson2jsonview, as long as the @controller returned in the method returned, you can get the specified view rendering.

return "testView";

For the view, here to say a word, different people have different preferences and habits, some projects like directly before and after the separation, some projects need to return some view template rendering basic framework, how to use the right way, no good or bad points, only the use of the scene is different, using the same view can play a role.

Above is simply explained some commonly used automatic configuration, as for more detailed configuration, we can take a look at the automatic configuration of the relevant source code, the idea of expansion is also beneficial. Because if you only want to quickly apply, the usual common configuration is sufficient, for the need to customize the application scenario, you can see the configuration changes.

Extending the Spring MVC configuration

The above is about the spring boot in the automatic configuration of MVC, in fact, you can see the original MVC configuration to view what the spring boot configuration items, you will find that the original already have, Now it's just another way: either by configuring or overriding the method to modify or increase the configuration of spring MVC. Here is an example of how to take over the configuration of spring-boot's spring MVC and configure a Fastjson converter in a modified manner.

How do I customize the MVC configuration in boot?

When a default configuration is required and a custom configuration is required, we need to customize the configuration, and Spring boot officially provides an adapter class Webmvcconfigureradapter to extend the functionality. The MVC configuration can be supported by overriding the interface.

@Configuration Public  class custommvcconfiguration extends webmvcconfigureradapter{//1    @Override     Public void configuremessageconverters(List//experiment found that does not work, may be the boot bug, or the official do not allow changes? }@Override     Public void extendmessageconverters(List for(httpmessageconverter<?> messageconverter:converters) {System.out.println (messageconverter);//2}    }}

1: Inheriting the parent class, is an adapter pattern class that can redefine the functionality and configuration of MVC, but does not affect the existing configuration, which is added to the expansion of functionality, do not know whether this is good or bad.
2: Find the extension method, you can add a custom method.

The actual combat 2--adds new functions to the existing automatic functions Fastjson

Fastjson, domestic, there are many people like to use, because the speed, simple operation. Before the old version is actually a lot of pits, but still very useful, support, and now the official version 1.2.12, and does not support the Spring boot starter, but it has httpmessageconvert support, in fact, to support is also very convenient. The following shows how to integrate.

Method 1: Register the Httpmessageconverts Bean directly

1. Create a new configuration file first.

//fastjsonhttpmessageconvertersconfiguration. Class@Configuration@ConditionalOnClass({Json.class})//1 Public  class fastjsonhttpmessageconvertersconfiguration {    @Bean     PublicHttpmessageconvertersfastjsonhttpmessageconverters() {Fastjsonhttpmessageconverter Fastconverter =NewFastjsonhttpmessageconverter ();//2Fastjsonconfig Fastjsonconfig =NewFastjsonconfig (); Fastjsonconfig.setserializerfeatures (Serializerfeature.prettyformat, Serializerfeature.writ        Eclassname);        Fastconverter.setfastjsonconfig (Fastjsonconfig); httpmessageconverter<?> converter = Fastconverter;return NewHttpmessageconverters (Converter); }

1. Determine if the JSON file exists and the configuration will be created.
2. I see the official document said that after the 1.2.10, there will be two methods to support Httpmessageconvert, one is Fastjsonhttpmessageconverter, support 4.2 of the following version, one is FASTJSONHTTPMESSAGECONVERTER4 support More than 4.2 of the version, specifically what the difference is not in-depth study.

2. Check if registration is successful.

It worked.

3, start. Executive Http://locahost:8080/showSetting

This method actually only registers the bean, because does not specify the execution configuration, uses the new method, this method actually is not good, cannot control flexibly. So let's see if we can specify the use like Gson, look at the picture:

, Httpmessageconvert automatically initializes Gson and Jackson when configured automatically, using Jackson as the default, and finds the configuration named: Spring.http.converters.preferred-json-mapper. So there's Method 2.

Method 2: Automatically configure the bean and specify the configuration item

1. Create a new configuration

//Fastjsonhttpmessageconvertersconfiguration.class//... Code for comment Method 1    @Configuration    @ConditionalOnClass({Fastjsonhttpmessageconverter.class})//1    @ConditionalOnProperty(//2Name = {"Spring.http.converters.preferred-json-mapper"}, Havingvalue ="Fastjson", matchifmissing =true)protected Static  class fastjson2httpmessageconverterconfiguration{        protected fastjson2httpmessageconverterconfiguration() {        }@Bean        @ConditionalOnMissingBean({Fastjsonhttpmessageconverter.class})//3         PublicFastjsonhttpmessageconverterFastjsonhttpmessageconverter() {Fastjsonhttpmessageconverter converter =NewFastjsonhttpmessageconverter (); Fastjsonconfig Fastjsonconfig =NewFastjsonconfig ();//4Fastjsonconfig.setserializerfeatures (Serializerfeature.prettyformat, Serializerfeat Ure.            Writeclassname, Serializerfeature.writemapnullvalue); Valuefilter Valuefilter =NewValuefilter () {//5                //o is class                //s is a key value                //o1 is value                 PublicObjectProcess(Object o, String S, Object O1) {if(NULL= = O1) {O1 =""; }returnO1;            }            };            Fastjsonconfig.setserializefilters (Valuefilter); Converter.setfastjsonconfig (Fastjsonconfig);returnConverter }    }

1: Determine if the class exists.
2: Use the Spring.http.converters.preferred-json-mapper property to start the function.
3: When this class is not registered, the bean is automatically registered.
4: Inject Fastjson serialization features using the latest official recommended configuration object.
5: Add filter for JSON value, because like mobile app, the service side is best not to pass the JSON value to NULL, but use "", this is a demonstration.

2. Specify the use of Fastjson.


3, start running, success. Now it is convenient to switch Fastjson or Gson.


This chapter mainly explains how to customize the MVC on the basis of custom configuration and integrate the new automatic configuration function, many students feel that the configuration is very simple basically enough, custom configuration what to do? The default configuration may just start to meet some requirements, but more time also need to customize the configuration for specific scenarios, such as interceptors and filters, although this section does not say, the actual use is a lot, but usually the rationale is figured out, more actual combat, there is no place to write the wrong, we talk more about communication.

Example of this chapter address: boot-properties

Page 168 of 366 in chapter 2016

Spring Boot Practice Toss (v): Custom configuration, extending the spring MVC configuration and using Fastjson

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.