Spring Boot Series (iii) Spring boot common annotations

Source: Internet
Author: User
Tags exception handling
Spring Boot series (iii) Spring boot common annotations

@RestController and @requestmapping

@RestController is called a stereotype (stereotype) annotation. It provides suggestions for developers who read the code. For spring, this class plays a special role. It inherits 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.


Example: In this example, the example class is a Web @Controller, so spring asks for it when it processes the incoming Web request.

Import org.springframework.boot.*;
Import org.springframework.boot.autoconfigure.*;
Import org.springframework.stereotype.*;
Import org.springframework.web.bind.annotation.*;
@RestController
@EnableAutoConfiguration
public class Example {
@RequestMapping ("/")
String Home () {
Return "Hello world!"; }
public static void Main (string[] args) throws Exception { springapplication.run (example.class, args); } }

@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. The note has six properties:


Params: Specifies that some parameter values must be included in the request before the method is processed.


Headers: Specifies that certain header values must be included in the request in order for the method to process requests.


Value: Specifies the actual address of the request, and the specified address can be the URI Template mode.


Method: Specifies the type of method requested, GET, POST, PUT, delete, and so on.


Consumes: Specifies the commit content type (Content-type) that handles the request, such as application/json,text/html.


Produces: Specifies the type of content returned, only if the specified type is included in the (Accept) type in the request header.


Instance:

@RequestMapping ("/test") 

Public String Test () { return "OK"; }

Note: @RestController and @requestmapping annotations are spring MVC annotations (they are not a specific part of spring boot)


@EnableAutoConfiguration

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 a web app is being developed and set up for spring accordingly.


Starter POMs and auto-configuration design auto-configuration are designed to better use "Starter POMs", but these two concepts are not directly linked. You are free to pick 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 annotation. It is recommended that you add it to the main @configuration class, and if you find that you are applying a specific automatic configuration class that you do not want, you can use the exclusion properties of the @enableautoconfiguration annotations to disable them.

Import org.springframework.boot.autoconfigure.*;
Import org.springframework.boot.autoconfigure.jdbc.*;
Import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration (Exclude={datasourceautoconfiguration.class})
public class Myconfiguration { //...
}

@Configuration

Spring Boot advocates Java-based configuration. Although you can use an XML source to invoke Springapplication.run (), it is recommended that you use the @configuration class as the primary source. The general definition of the Main method class is also a good candidate for the main @configuration.


It is not necessary to put all the @configuration into a separate class. @Import annotations can be used to import other configuration classes. You can also use @componentscan annotations to automatically collect all spring components, including the @configuration class.


If you need to use XML-based configuration, the official recommendation still starts with a @configuration class. The XML configuration file can be loaded with additional @importresource annotations.


@Configuration annotations The class, which is equivalent to the configuration beans in XML, and the @bean annotation method is equivalent to configuring the bean in XML.

@ComponentScan (basepackages = "Com.yoodb.blog", includefilters = {@ComponentScan. Filter (Aspect.class)})


@ComponentScan: Indicates that the class is automatically discovered by the scan component. If you scan to a @component,

These annotated classes, such as @Controller, @Service, and registered as beans, can automatically collect all the spring components, including the @configuration class.


Search for beans using @componentscan annotations and import them in conjunction with @autowired annotations. All spring components, including the @configuration class, can be automatically collected. If it is not configured, Spring boot scans the class that uses @service, @Repository, and so on, under the package where the startup class is located and under the sub-package.


@SpringBootApplication

Many spring boot developers always use @configuration, @EnableAutoConfiguration and @componentscan to annotate their main class. Since these annotations are used so frequently (especially if you follow these best practices), Spring boot provides a convenient @springbootapplication choice.


The @springbootapplication annotation is equivalent to using @configuration, @EnableAutoConfiguration, and @componentscan with default properties.

Import org.springframework.boot.SpringApplication;
Import org.springframework.boot.autoconfigure.SpringBootApplication;

Equivalent to @configuration @EnableAutoConfiguration @ComponentScan

public class Application {public static void Main (string[] args) { Springapplication.run (Applicatio  N.class, args); }   }

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 the @configurationproperties class:

@Component
@ConfigurationProperties (prefix= "Connection")
public class ConnectionSettings { @NotNull private inetaddress remoteaddress; //... getters and setters
}

@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.

@Configuration
@Profile ("production") public
class Productionconfiguration {
 //...
}

Global exception Handling

@ControllerAdvice: Contains @component. can be scanned to. Handles exceptions uniformly.

@ExceptionHandler (Exception.class): Use the method above to indicate that you have encountered this exception to perform the following methods.

/** 
 * Global exception Handling */ 
 @ControllerAdvice public class Globaldefaultexceptionhandler {public
 static final Stri  ng Default_error_view = "ERROR";
 @ExceptionHandler ({typemismatchexception.class,numberformatexception.class}) public
 Modelandview Formaterrorhandler (httpservletrequest req, Exception e) throws Exception {
 Modelandview mav = new Modelandvie  W ();  
 mav.addobject ("error", "wrong parameter type");  
 Mav.addobject ("exception", e);  
 mav.addobject ("url", Requestutils.getcompleterequesturl (req));  
 mav.addobject ("timestamp", new Date ());  
 Mav.setviewname (Default_error_view);  
 return MAV;
 }
}

Use @value annotations to read the configuration inside the application.properties, using the example reference:

/************** application.properties *************/

qq_api_key=********1*********** qq_api_secrt=** 2***********

/************* Java **************/
@Value ("${qq_api_key}")  
Private String API _key;  
@Value ("

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.