Spring Boot Common Annotations Summary
@RestController and @requestmapping annotations
@RestController annotations, which inherit from @controller annotations. 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 the use of @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:
1 @Target (value=type) 2 @Retention (value=runtime) 3 @Documented 4 @Controller 5 @ResponseBody 6
Note: @RestController and @RequestMapping annotations are spring MVC annotations (they are not a specific part of spring boot)
@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.
1 <Prename= "Code"class= "Java">import org.springframework.boot.autoconfigure.*; 2 import org.springframework.boot.autoconfigure.jdbc.*; 3 import org.springframework.context.annotation.*; 4 @Configuration5 @EnableAutoConfiguration (Exclude={datasourceautoconfiguration.class})6 Public class Myconfiguration {7}
@Configuration
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, equivalent to the configuration of beans in XML; The @bean annotation method is equivalent to configuring the Bean in XML
1 @ComponentScan (basepackages = "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.
1 PackageCom.example.myproject; 2 Importorg.springframework.boot.SpringApplication; 3 Importorg.springframework.boot.autoconfigure.SpringBootApplication; 4@SpringBootApplication//Same as @Configuration @EnableAutoConfiguration @ComponentScan5 Public classApplication {6 Public Static voidMain (string[] args) {7Springapplication.run (Application.class, args); 8 } 9}
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:
1 @Component 2 @ConfigurationProperties (prefix= "Connection") 3 public class connectionsettings { 4 @NotNull 5 Private inetaddress remoteaddress; 6 // ... getters and Setters 7 }
@Profiles
Spring 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.
1 @Configuration 2 @Profile ("Production") 3public class productionconfiguration { 4// ... 5 }
@ResponseBody
Indicates that the return result of the method is written directly to the HTTP response body
Typically used when fetching data asynchronously, after using @requestmapping, the return value usually resolves to a jump path, plus
After @responsebody, the returned results are not resolved to the jump path, but are written directly to the HTTP response body. Like what
Asynchronously gets the JSON data, plus @responsebody, which returns the JSON data directly.
@Component:We can use this annotation to annotate components when they are poorly categorized. General public methods I'm going to use this note.@AutoWiredBytype Way. The configuration of the bean to use, the completion of the properties, methods of assembly, it can be on the class member variables, methods and structure
Make the function of labeling, complete the work of automatic assembly.
When added (Required=false), even if the bean can not find the error.@RequestParam:
Used in front of the method's parameters. 1 @RequestParam String a =request.getparameter ("a")
@PathVariable:
The PATH variable.
1 Requestmapping ("user/get/mac/{macaddress}") 2public String Getbymacaddress (@PathVariable String macAddress) { 3 //dosomething; 4 }
The arguments are the same as the names in the curly braces. Demonstration of the above annotations
1 /** 2 * The Controller class for users to comment and manage comments;3 */ 4 @Controller5@RequestMapping ("/msgcenter") 6 Public classMycommentcontrollerextendsBasecontroller {7 @Autowired8 Commentservice Commentservice; 9 Ten @Autowired One Operatorservice Operatorservice; A - /** - * Add activity comments; the * - * @paramApplyid activity ID; - * @paramcontent comments; - * @return + */ - @ResponseBody +@RequestMapping ("/addcomment") A PublicMap<string, Object> addcomment (@RequestParam ("Applyid") Integer Applyid, @RequestParam ("content") (String content) { at .... - returnresult; - } -}
1 @RequestMapping ("/list/{applyid}") 2 public String list (@PathVariable Long Applyid, httpservletrequest request, Modelmap Modelmap) { }
Global handling of exceptions:@ControllerAdvice:Contains @component. can be scanned to.
Handles exceptions uniformly.
@ExceptionHandler (Exception.class):
Use the method above to indicate that you are encountering this exception by performing the following methods.
1 /** 2 * Global Exception handling3 */ 4 @ControllerAdvice5 classGlobaldefaultexceptionhandler {6 Public Static FinalString Default_error_view = "ERROR"; 7 8@ExceptionHandler ({typemismatchexception.class, NumberFormatException.class}) 9 PublicModelandview Formaterrorhandler (httpservletrequest req, Exception e)throwsException {TenModelandview Mav =NewModelandview (); OneMav.addobject ("error", "parameter type wrong"); AMav.addobject ("Exception", E); -Mav.addobject ("url", Requestutils.getcompleterequesturl (req)); -Mav.addobject ("timestamp",NewDate ()); the Mav.setviewname (Default_error_view); - returnMav; -}}
Read the configuration inside the application.properties by @value annotations
1 # face++ key 2 face_api_key = r9z3vxc7zcxfewgvrjoyrvu1d-qr**** 3 Face_ Api_secret =d9wuqgcylvocidsbx35uth********
1 @Value ("${face_api_key}") 2 private String api_key; 3 4 @Value ("${face_api_secret}") 5 private String Api_secret;
Note that when using this annotation, a class that uses @value, if referenced by another class as an object, must use the injection method instead of new.
So the common configuration is configured in the Application.properties file.
Spring Boot Common Annotations Summary