Home>

@restcontroller and @requestmapping annotations

An important new improvement in 4.0 is the @restcontroller annotation, which inherits from the @controller annotation. Versions before 4.0,Spring mvc components use @controller to identify the current class as a controller servlet. Using this feature,We can develop rest services without using @controller and special @restcontroller.

When you implement a restful web service, the response will always be sent through the response body. To simplify development,Spring 4.0 provides a specialized version of the controller. Let's take a look at the definition of @restcontroller implementation:

@target (value=type)
 @retention (value=runtime)
 @documented
 @controller
 @responsebody
public @interface restcontroller
@target (value=type)
 @retention (value=runtime)
 @documented
 @controller
 @responsebody
public @interface restcontroller

The @requestmapping annotation provides routing information.It tells spring that any http request from the "/" path should be mapped to the home method. @restcontroller annotation tells spring to render the result as a string,And return directly to the caller.

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

@enableautoconfiguration annotation

The second class-level annotation is @enableautoconfiguration. This annotation tells spring boot to guess how i want to configure spring based on the added jar dependencies. Since spring-boot-starter-web adds tomcat and spring mvc, auto-configuration will assume that you are developing a web application and set up spring accordingly.starter poms and auto-configuration:The purpose of designing auto-configuration is to better use "starter poms", but the two concepts are not directly related.You are free to pick jar dependencies other than starter poms, and Spring Boot will still do its best to automatically configure your application.

You can choose automatic configuration by adding @enableautoconfiguration or @springbootapplication annotations to a @configuration class.

Note:You only need to add a @enableautoconfiguration annotation. We recommend that you add it to the main @configuration class.

If you find a specific auto-configuration class that you don't want applied,You can disable them using the exclude attribute of the @enableautoconfiguration annotation.

<pre name="code">import org.springframework.boot.autoconfigure. *;
import org.springframework.boot.autoconfigure.jdbc. *;
import org.springframework.context.annotation. *;
@configuration
@enableautoconfiguration (exclude=(datasourceautoconfiguration.class))
public class myconfiguration {
}
<pre name="code">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 a xml source to call springapplication.run (), we generally recommend that you use the @configuration class as your primary source.Classes that generally define a main method are also a good candidate for the main @configuration.You don't need to put all @configuration into a single class. The @import annotation can be used to import other configuration classes.Alternatively, you can use the @componentscan annotation to automatically collect all spring components, including the @configuration class.

If you absolutely need to use XML-based configuration, we recommend that you still start with a @configuration class. You can load the xml configuration file with the additional @importresource annotation.

@configuration annotation for this class,Equivalent to configuring beans in XML;using the @bean annotation method is equivalent to configuring beans in XML

@componentscan (basepackages="com.hyxt", includefilters={@ componentscan.filter (aspect.class)})
@componentscan (basepackages="com.hyxt", includefilters={@ componentscan.filter (aspect.class)})
@springbootapplication

Many spring boot developers always annotate their main classes with @configuration, @enableautoconfiguration and @componentscan. Since these annotations are used so frequently together (especially when you follow the best practices above), spring boot provides a convenient @springbootapplication option.

The @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, args);
  }
}
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, args);
  }
}

spring boot will try to verify the external configuration,Use jsr-303 by default (if in the classpath). You can easily add jsr-303 javax.validation constraint annotation to your @configurationproperties class:

@component
@configurationproperties (prefix="connection")
public class connectionsettings {
@notnull
private inetaddress remoteaddress;
//... getters and setters
}
@component
@configurationproperties (prefix="connection")
public class connectionsettings {
@notnull
private inetaddress remoteaddress;
//... getters and setters
}
@profiles
Spring profiles provide a way to isolate application configuration,And make these configurations only take effect in specific environments.
Any @component or @configuration can be marked by @profile, which limits when it can be loaded.
[java] view plain copy print?
@configuration
@profile ("production")
public class productionconfiguration {
//...
}
@configuration
@profile ("production")
public class productionconfiguration {
//...
} @responsebody

Indicates that the return result of this method is written directly into the http response body

Generally used when fetching data asynchronously,After using @requestmapping, the return value usually resolves to a jump path,Plus

The result returned by @responsebody will not be parsed as a jump path,Instead, it is written directly into the http response body. such as

Get json data asynchronously, after adding @responsebody, it will directly return json data.

@component:

Broadly referring to components,When components are not well classified,We can use this annotation for annotation.Generally public methods I will use this annotation

@autowired

bytype way. Use the configured beans to complete the assembly of properties and methods.It can be used for class member variables, methods and constructs

Build functions to label,Complete the work of automatic assembly.

When (required=false) is added, no error is reported even if the bean cannot be found.

@requestparam:

Used before the parameters of the method.

@requestparam string a=request.getparameter ("a").
@requestparam string a=request.getparameter ("a").

@pathvariable:

Path variable.

requestmapping ("user/get/mac/{macaddress}")
public string getbymacaddress (@pathvariable string macaddress) {
//do something;
}
requestmapping ("user/get/mac/{macaddress}")
public string getbymacaddress (@pathvariable string macaddress) {
//do something;
}

The parameters are the same as the names in the curly braces.

Demonstration of the above annotations

/**
 * The controller class for user reviews and management of reviews;
 * /
@controller
@requestmapping ("/msgcenter")
public class mycommentcontroller extends basecontroller {
  @autowired
  commentservice commentservice;
  @autowired
  operatorservice operatorservice;
  /**
   * Add event reviews;
   *
   * @param applyid activity id;
   * @param content comment content;
   * @return
   * /
  @responsebody
  @requestmapping ("/addcomment")
  public map<string, object>addcomment (@requestparam ("applyid") integer applyid, @requestparam ("content") string content) {
    ....
    return result;
  }
}
/**
 * The controller class for user reviews and management of reviews;
 * /
@controller
@requestmapping ("/msgcenter")
public class mycommentcontroller extends basecontroller {
  @autowired
  commentservice commentservice;
  @autowired
  operatorservice operatorservice;
  /**
   * Add event reviews;
   *
   * @param applyid activity id;
   * @param content comment content;
   * @return
   * /
  @responsebody
  @requestmapping ("/addcomment")
  public map<string, object>addcomment (@requestparam ("applyid") integer applyid, @requestparam ("content") string content) {
    ....
    return result;
  }
}
@requestmapping ("/list/{applyid}")
  public string list (@pathvariable long applyid, httpservletrequest request, modelmap modelmap) {
}
 @requestmapping ("/list/{applyid}")
  public string list (@pathvariable long applyid, httpservletrequest request, modelmap modelmap) {
}

Handling exceptions globally:

@controlleradvice:

Contains @component. Can be scanned.

Handle exceptions uniformly.

@exceptionhandler (exception.class):

Used in the method above means that the following method is executed when this exception is encountered.

/**
 * Global exception handling
 * /
@controlleradvice
class globaldefaultexceptionhandler {
  public static final string default_error_view="error";
  @exceptionhandler ((typemismatchexception.class, numberformatexception.class))
  public modelandview formaterrorhandler (httpservletrequest req, exception e) throws exception {
    modelandview mav=new modelandview ();
    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;
  }}
/**
 * Global exception handling
 * /
@controlleradvice
class globaldefaultexceptionhandler {
  public static final string default_error_view="error";
  @exceptionhandler ((typemismatchexception.class, numberformatexception.class))
  public modelandview formaterrorhandler (httpservletrequest req, exception e) throws exception {
    modelandview mav=new modelandview ();
    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 annotation to read the configuration in application.properties

#face ++ key
face_api_key=r9z3vxc7zcxfewgvrjoyrvu1d-qr ****
face_api_secret=d9wuqgcylvocidsbx35uth ********
#face ++ key
face_api_key=r9z3vxc7zcxfewgvrjoyrvu1d-qr ****
face_api_secret=d9wuqgcylvocidsbx35uth ********
@value ("${face_api_key}")
  private string api_key;
  @value ("${face_api_secret}")
  private string api_secret;
 @value ("${face_api_key}")
  private string api_key;
  @value ("${face_api_secret}")
  private string api_secret;so commonly used configuration is configured in the application.properties file
  • Previous Object inheritance in JavaScript
  • Next Datagridview use skills (9) Right-click menu of Datagridview