1, @RestController and @requestmapping annotations
4.0 important A new improvement is the @restcontroller annotation, which inherits from the @controller annotation.
Prior to 4.0, Spring MVC components used @controller to identify the current class as a controller servlet. With this feature, we can develop rest services without using @controller, and dedicated @restcontroller.
When you implement a RESTful Web services, response will always be sent through the response body. To simplify development, Spring 4.0 provides a dedicated version of the controller. Let's take a look at the definition of @restcontroller implementation:
@Target (value=TYPE) @Retention (Value=RUNTIME) @Documented @Controller Public @interface Restcontroller
@RequestMapping annotations provide routing information. It tells Spring that any HTTP requests from the "/" path should be mapped to the home method.
@RestController annotation tells spring to render the result as a string and return it directly to the caller.
Note: @RestController and @RequestMapping annotations are spring MVC annotations (they are not a specific part of spring boot)
2. @EnableAutoConfiguration annotations
The second class-level annotation is @EnableAutoConfiguration. This note tells spring boot to guess how you want to configure spring based on the added jar dependency.
Because Spring-boot-starter-web adds Tomcat and spring MVC, Auto-configuration will assume that you are developing a web app and setting up spring accordingly.
Starter POMs and Auto-configuration: The purpose of design auto-configuration is to better use "Starter POMs", but these two concepts are not directly linked. You are free to choose a jar dependency other than starter Poms, and spring boot will still do its best to automatically configure your app.
You can select automatic configuration by adding @EnableAutoConfiguration or @SpringBootApplication annotations to a @Configuration class.
Note: You only need to add a @EnableAutoConfiguration note. We recommend that you add it to the main @Configuration class.
If you find that you have applied specific auto-configuration classes that you do not want, you can disable them by using the exclusion properties of the @EnableAutoConfiguration annotations.
Import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc. *; Import org.springframework.context.annotation. *; @Configuration @enableautoconfiguration (Exclude={datasourceautoconfiguration. Classpublicclass
Spring Boot advocates Java-based configuration. Although you can use an XML source to invoke Springapplication.run (), we generally recommend that you use @Configuration class as the primary source. The general definition of the Main method class is also a good candidate for the main @Configuration. You don't need to put all the @Configuration into a separate class. @Import annotations can be used to import other configuration classes. Alternatively, you can use @ComponentScan annotations to automatically collect all of the spring components, including @Configuration classes.
If you absolutely need to use XML-based configuration, we recommend that you still start with a @Configuration class. You can load an XML configuration file with additional @ImportResource annotations.
@Configuration annotation of this class, the equivalent XML configuration beans; Using the @bean annotation method is equivalent to configuring the Bean in XML
" Com.hyxt ", includefilters = {@ComponentScan. Filter (Aspect. Class)}) @SpringBootApplication
Many spring boot developers always use @Configuration, @EnableAutoConfiguration and @ComponentScan annotate their main class. Because these annotations are used so frequently (especially if you follow these best practices), Spring boot provides a convenient @SpringBootApplication choice.
This @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with default properties.
package com.example.myproject; import Org.springframework.boot.SpringApplication; Import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @ Configuration @EnableAutoConfiguration @ComponentScan public class application { Public static void main (string[] args) {springapplication.run (application. ) class
Spring Boot will attempt to validate the external configuration by default with JSR-303 (if in the Classpath path). You can easily add JSR-303 javax.validation constraint annotations to your @configurationproperties class
@Component @configurationproperties (prefix="Connection") Public classconnectionsettings {@NotNullPrivateinetaddress remoteaddress;//. .. getters and Setters} @ProfilesSpring Profiles provides a way to isolate application configurations and allow these configurations to take effect only in a specific environment. Any @component or @configuration can be @profile labeled, limiting the timing of loading it. [Java] View plain copy print?On code, View the snippet that derives from my code slice @Configuration @profile ("Production") Public classproductionconfiguration {// ... }
@ResponseBody
Indicates that the return result of the method is written directly to the HTTP response body
Generally used when retrieving data asynchronously, after using @requestmapping, the return value is usually resolved to the jump path, plus @responsebody returns the result will not be resolved to the jump path, but directly to the HTTP response body. For example: asynchronously fetching JSON data, plus @responsebody, will return the JSON data directly .
3. @Component:
We can use this annotation to annotate components when they are poorly categorized. General public methods I'm going to use this note.
4. @AutoWired
Bytype Way. The configuration of the bean to use, the completion of the properties, methods of assembly, it can be the class member variables, methods and constructors to label, complete the work of automatic assembly.
When added (Required=false), even if the bean can not find the error.
5. @RequestParam:
Used in front of the method's parameters.
@RequestParam String a =request.getparameter ("a")
6. @PathVariable:
Path variable
Requestmapping ("user/get/mac/{macaddress}" Public // Do something;
The arguments are the same as the names in the curly braces.
Demonstration of the above annotations
/** * The Controller class for users to comment and manage comments;*/@Controller @requestmapping ("/msgcenter") Public classMycommentcontroller extends Basecontroller {@Autowired commentservice commentservice; Automatic assembly service class @Autowired Operatorservice operatorservice; /** * Add activity comments, * * @param applyid activity ID; * @param content comments; * @return*/@ResponseBody //Asynchronously gets the JSON data, plus @responsebody directly returns the JSON data @RequestMapping ("/addcomment")//requested routing information PublicMap<string, Object> addcomment (@RequestParam ("Applyid") Integer Applyid, @RequestParam ("content"String content) {....returnresult; }} @RequestMapping ("/list/{applyid}") PublicString list (@PathVariable Long Applyid, httpservletrequest request, Modelmap modelmap) {}
Global handling of exceptions:
7. @ControllerAdvice:
Contains @component. can be scanned to.
Handles exceptions uniformly.
8, @ExceptionHandler (Exception.class):
Use the method above to indicate that you are encountering this exception by performing the following methods.
/** * Global exception handling*/@ControllerAdviceclassGlobaldefaultexceptionhandler { Public StaticFinal String Default_error_view ="Error"; @ExceptionHandler ({typemismatchexception.class, NumberFormatException.class}) PublicModelandview Formaterrorhandler (httpservletrequest req, Exception e) throws Exception {Modelandview Mav=NewModelandview (); Mav.addobject ("Error","wrong parameter type"); Mav.addobject ("Exception", E); Mav.addobject ("URL", Requestutils.getcompleterequesturl (req)); Mav.addobject ("timestamp",NewDate ()); Mav.setviewname (Default_error_view); returnMav; }}
9. @value
Read the configuration inside the application.properties by @value annotations
#face ++ =r9z3vxc7zcxfewgvrjoyrvu1d-qr**** =d9wuqgcylvocidsbx35uth********@Value ( "${face_api_key}")private String api_key; @Value ( " ${face_api_secret} " )private String api_secret; so commonly used configurations are configured in the Application.properties file
Spring Boot common Annotations Usage Summary