Commonly used annotations

1. Create projects

Project name: 01-spring-boot-MVC

2.@SpringBootApplication

@springBootApplication is used in the SpringBoot project boot program, the entire SpringBoot only and must have one such annotation, is the project entry program.

The following code looks like this:

Source: the SRC/main/Java/com/springboot codingstudty/MainApplication Java

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) { SpringApplication.run (Demo01Application.class, args); }}Copy the code

@SpringBootApplication is a combination of the following three annotations:

@Configuration

@EnableAutoConfiguration

@ComponentScan
Copy the code

@SpringBootApplication equals all three of these annotations, as described in the listing above.

3.@Controller

@Controller is to return a URL request to a specific page, such as an HTML, JSP page, etc. This annotation is added to the class head.

The following is an example of http://localhost to index.html, which requires 3 steps.

(1) To enable SpringBoot to access HTML, JSP and other pages, you need to configure the application

Source: SRC/main/resources/application. The properties

# default findstaticPrefix =/ spring.mvc.view.suffix=.htmlCopy the code

(2) create index.html at static

Source: SRC/main/resources/static/index. The HTML

<div>

    <h3>Home page</h3>

    <div>The content of the home page...</div>

</div>
Copy the code

(3) write CodingStudyIndexController controller

The source code:

src/main/java/com/springboot/codingstudty/controller/CodingStudyIndexController.java

@Controller
public class CodingStudyIndexController {}Copy the code

(4) Cooperate with @RequestMapping for specific page jump control:

Jump to the index.html page

The source code:

src/main/java/com/springboot/codingstudty/controller/CodingStudyIndexController.java

/** * No data render returns *@return* /
@RequestMapping("/")
public String index01(a) {
    return "index";
}
Copy the code

Note: Controller data rendered to the page needs to return ModelAndView as follows:

The source code:

src/main/java/com/springboot/codingstudty/controller/CodingStudyIndexController.java

/** * returns ModelAndView * Through which data can be brought in and rendered to the page *@return* /
@RequestMapping("/index")
public ModelAndView index(a){
    ModelAndView modelAndView = new ModelAndView ();
    // Data can be set
    String data = "This data comes from IndexController...";
    modelAndView.addObject("data",data);
    // Jump to the index.html page
    modelAndView.setViewName ("index");
    return modelAndView;
}
Copy the code

At this point, there are several ways to get data from the index. HTML page.

  • The first option: introduce a freemark template;
  • The second scheme is to introduce the Thymeleaf template.
  • The third scheme: establish JSP pages, and so on;

Because the syntax of the first scheme is simple and the frequency of use is high, the first scheme is briefly described below.

Introduce dependencies in POM.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
Copy the code

In the application.properties configuration:

################## Freemarker template configuration
# suffix
spring.freemarker.suffix=.html

Templates by default
spring.freemarker.template-loader-path=classpath:/static/

# the req access request
spring.freemarker.request-context-attribute=req
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
Copy the code

After this configuration, the code for retrieving data from index. HTML is:

${data} /div> </div>Copy the code

Since this chapter isn’t about how freemarker works, I’ll leave it at that.

There are a few other things to note: The @Controller needs to configure the path before it can find the page. There are several ways to configure the mapping HTML page. Here are the four ways:

1) Static by default:

Map HTML pages
#========1. Default ===============================
Static = static;
spring.mvc.view.prefix=/

spring.mvc.view.suffix=.html
Copy the code

2) Point to a new path, such as the views path

# You can change the static-locations mapping path as follows:
#========2, will find the file under the views ====================
spring.mvc.view.prefix=/

spring.mvc.view.suffix=.html

spring.resources.static-locations=classpath:/views/
Copy the code

3) Point to a new path, such as under the public path

#========3, find the file in public ====================
spring.mvc.view.prefix=/

spring.mvc.view.suffix=.html

spring.resources.static-locations=classpath:/public/
Copy the code

4) Point to a new road force, as under taenta -INF/resource

/ meta-INF /resources/ ======
spring.mvc.view.prefix=/

spring.mvc.view.suffix=.html

spring.resources.static-locations=classpath:/META-INF/resources/
Copy the code

Regardless of the Settings, the above paths must be under SRC /main/resource.

4.@RestController

@restController is a new annotation, which is a combination of @Controller and @responseBody.

After the @restController annotation, the @requestMapping method can return Json data.

(1) the new CodingStudyRestController controller:

The source code:

src/main/java/com/springboot/codingstudty/controller/CodingStudyRestController.java

@RestController
public class CodingStudyRestController {
/** * if you want to get user information *@return* /
@GetMapping("user")
public Map<String,Object> getUser(a) {
    // Impersonate a user
    Map<String,Object> user = new HashMap<>();
    user.put ("id".1);
    user.put ("name"."Zhang");
    user.put ("age".18);
    // Return the user
    returnuser; }}Copy the code

Running results:

5.@RequestMapping

The @requestMapping annotation is used in the Controller method header as follows:

Source: the SRC/main/Java/com/springboot/codingstudty/controller/CodingStudyIndexController Java

@RequestMapping("/index")
public ModelAndView index(a){
    ModelAndView modelAndView = new ModelAndView ();
    // Data can be set
    String data = "This data comes from IndexController...";
    modelAndView.addObject("data",data);
    // Jump to the index.html page
    modelAndView.setViewName ("index");
    return modelAndView;
}
Copy the code

Spring Boot has GetMapping, PostMapping, PutMapping, and DeleteMapping to replace it.

6.@RequestParam

Set before the parameter in the format:

@requestParam (value= "variable name", Required =true/false, defaultVale= default)
Copy the code
  1. Value: request parameter name (must be configured)
  2. Required: Whether or not this parameter is required, the default is true, that is, it must be included in the request, if not, an exception will be thrown (optional configuration)
  3. DefaultValue: the defaultValue, if set, required is automatically set to false, false regardless of whether or not you configure required and what value is configured (optional)

Set required = false

For example, creating a RequestParamController:

The source code:

src/main/java/com/springboot/codingstudty/controller/RequestParamController.java

@GetMapping("param")
public String param(

    @RequestParam("id") String id,
    @RequestParam(value = "name", required = false) String name,
    @RequestParam(value = "age", required = false) int age){
        String data = "";
    try {
        // Return ID, NAME, age
        data = "id=" + id + ",name=" + name + ",age=" + age;
    } catch (Exceptione){
        data = e.getMessage();
    }
   return data;
}
Copy the code

The following url must have the id parameter. Otherwise, an error will be reported. Id = 1).

@RequestParam("id") String id
Copy the code
  • When only value is set, value can be omitted.
  • If you want to set multiple parameter values, value cannot be omitted.
  • Required defaults to true, meaning the value must be passed, and an error is reported if no value is passed.

The second parameter: the following URL can not have the userName parameter, request no error.

@RequestParam(value="userName", required=false) String userName
Copy the code

Age = null. Int is an underlying type that does not accept null.

@RequestParam(value="age", required=false) int age
Copy the code

Running results:

7.@PathVariable

Create a PathVariableController controller class.

The source code:

src/main/java/com/springboot/codingstudty/controller/PathVariableController.java

Set before the parameter in the format:

@pathVariable (value= "variable name", Required =true/false)
Copy the code
  1. Value: request parameter name (must be configured)
  2. Required: Whether this parameter is required. The default is true, that is, it must be included in the request. If not, it will

Throwing an exception (Optional configuration)

Specific methods:

@GetMapping("path/{id}/{name}")
public String pathVar(
    @PathVariable("id") String id,
    @PathVariable(value = "name",required = false) String userName){
        return "id="+id+"And the userName ="+userName;
}
Copy the code

Passing parameters, such as: zhang at http://localhost:8086/path/1/

Note: The request path must be complete, otherwise an error is reported.

The results

8.@GetMapping

In the following example of @getMapping, @postMapping, @putMapping, and @deletemapping tests, create a controller class, UserController

The source code:

src/main/java/com/springboot/codingstudty/controller/UserController.java

@getMapping is a composite annotation that is short for @requestMapping (method = requestMethod.get) and only receives front-end GET requests.

@GetMapping
public Map<String,Object> getUser(a) {
    Map<String,Object> user = new HashMap<>();
    user.put("id".1);
    user.put("name"."ming206");
    return user;
}
Copy the code

9.@PostMapping

PostMapping is a combination of @requestMapping (Method = requestMethod. POST) annotations. PostMapping only receives front-end POST submissions and is generally used to add data.

@PostMapping
public boolean insert(@RequestBody User user) {
    //insert ...
    return true;
}
Copy the code

10. @PutMapping

@putMapping is a combination annotation, which is short for @requestMapping (Method = RequestMethod.PUT). It only receives front-end PUT submissions and is generally used to modify data.

@PutMapping
public boolean update(@RequestBody User user) {
    //update .....
    return true;
}
Copy the code

11. @DeleteMapping

@deletemapping is a composite annotation, short for @requestMapping (method = requestMethod.delete), which only accepts front-end DELETE submissions for data deletion.

@DeleteMapping
public boolean del(@PathVariable("id") String id) {
    System.out.println(id);
    //delete ....
    return true;
}
Copy the code

12. @ResponseBody

The @responseBody annotation is typically used on controller methods to write the return value of the method to the body area of the response in a specific format and return the data to the client. When the ResponseBody is not written above the method, the bottom layer encapsulates the method’s return value as a ModelAndView object.

You don’t need this annotation in @RestController of Spring Boot, which says that @RestController is a combination of @Controller and @responseBody. Read RestController.

Here is a comment in front of the method body of the @Controller modified class:

Source: the SRC/main/Java/com/springboot/codingstudty/controller/UserViewController Java

@GetMapping("json")
@ResponseBody
public Map<String,Object> getJson(a){
    // Impersonate a user
    Map<String,Object> user = new HashMap<> ();
    user.put ("id".100);
    user.put("name"."ResponseBody");
    user.put("age".25);
    // Return the user
    return user;
}
Copy the code

Running results:

13. @RequestBody

@requestBody is used to receive data from the JSON string passed from the front end to the back end. If @RequestBody is used to receive data, the front end cannot submit data in GET mode. Instead, it submits data in POST mode.

@requestBody and @RequestParam() can be used together in the same receiving method on the back end. @RequestBody can have at most one and @RequestParam() can have more than one.

For example:

Source: the SRC/main/Java/com/springboot/codingstudty/controller/UserController Java

@PutMapping

public boolean update(@RequestBody User user) {
    //update .....
    return true;
}

@PostMapping("save")
public String save(
    @RequestParam("id") String id,
    @RequestParam(value="age", required=false) int age,
    @RequestBody User user){
        return "id="+id+",age="+age+". The user object = = >"+user.toString (); 
    }
Copy the code

The User model:

@Data

public class User {
    int id;
    String name;
    String age;
}
Copy the code

Running results:

The above API test tool is PostMan

14. @CrossOrigin

A common problem with the front-end Ajax request back end after the front and back end are separated is cross-domain problems. There are several ways to solve this problem. Here are two solutions:

Method 1: Annotate the method header with @crossorigin

@GetMapping("isCheck")
@CrossOrigin
public R<List<Resource>> selectAll(@RequestParam("ids") String ids) {
    return R.ok (this.resourceService.getListByIds (ids));
}
Copy the code

Method 2: Use filter Settings:

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/AccessControlAllowOriginFilter. Java

package com.springboot.codingstudty.configuration;

import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/** * Resolve cross-domain issues */

@Configuration
public class AccessControlAllowOriginFilter implements Filter {

    @Override
    public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain)
              throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin"."*");
        response.setHeader("Access-Control-Allow-Methods"."POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Credentials"."true");
        chain.doFilter(req, response);
}
public void init(FilterConfig filterConfig) {
    System.out.println("Initial configuration......");
}

public void destroy(a) {
    System.out.println("Destruction..."); }}Copy the code

15. @Configuration

@Configuration is the definition Configuration class, which is typically registered with an @bean inside the class, meaning that manual new is not required for future calls. Let’s try it out in three steps.

(1) Define a class, which is a normal class.

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/UserAction. Java

public class UserAction {
    public String display(a){
        return "Execute UserAction display.... "; }}Copy the code

(2) Define the configuration class and register the bean

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/MyConfiguration. Java

@Configuration
public class MyConfiguration {

/ / the default
@Bean
UserAction userAction(a){
    System.out.println ("The default name is userAction");
        return new UserAction();
    }
    / /...
}
Copy the code

Note:

  • Class header annotation @Configuration
  • And the method inside of it has @ beans.

(3) Call UserAction class

Call the test on the Controller class. Note that no matter where the call is made, the final run must depend on the Spring container or it will not run. For example, null-pointer exceptions are raised in the normal main method, but are allowed in the Controller and Test classes, whose environments depend on the Spring container.

Call with the annotation @autowired on the variable to retrieve the bean instance.

Create UserActionController class

The source code:

src/main/java/com/springboot/codingstudty/controller/UserActionController.java

// With the Autowired annotation, no new object is required

@Autowired
UserAction userAction;

@GetMapping("user/display")
public String getDisplay(a) {
    return userAction.display();
}
Copy the code

Request print effect on the browser side:

You can also write methods to get beans by hand, creating a new class, CreateBean class

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/CreateBean. Java

@Component
public class CreateBean implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
                throws BeansException {this.applicationContext=applicationContext; }public ApplicationContext getApplicationContext(a) {
        returnapplicationContext; }}Copy the code

At this point, call within UserActionController:

Source: the SRC/main/Java/com/springboot/codingstudty/controller/UserActionController Java

@Autowired
CallBean callBean;

@GetMapping("user/display2")
public String getDisplay2(a){

    // The name of the bean when registered, which is a string
    String beanName = "userAction";
    UserAction userAction = callBean.getApplicationContext ()
            .getBean (beanName,UserAction.class);

    String msg = userAction.display ();

    return "Get bean== manually"+msg;
}
Copy the code

Request print effect on the browser side:

16. @Bean

The @bean annotation has been used many times above, so I won’t go into it here, so LET’s go straight to the example.

(1) The default registered bean, the above code also has, as follows

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/MyConfiguration. Java

/ / the default
@Bean
UserAction userAction(a){
    System.out.println ("The default name is userAction");
    return new UserAction();
}
Copy the code

(2) Specify a bean name

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/MyConfiguration. Java

@Bean(value = "userAction1")
UserAction userAction1(a){
    System.out.println ("Name is userAction1");
    return new UserAction();
}
Copy the code

(3) The call is to specify the bean name

Source: the SRC/main/Java/com/springboot/codingstudty/controller/UserActionController Java

Use the @ the Resource

@Resource(name = "userAction1")
UserAction userAction;
Copy the code

Or the @autowired + @ the Qualifier

@Autowired
@Qualifier(value = "userAction1")
UserAction userAction;
Copy the code

17. @Service

A component that decorates the Service layer, annotated on a class. Note that it is not marked on the interface.

/** * Description: service layer *@author ming
*/

@Service
public class UserService {
    //TODO
}
Copy the code

After that, you can call @AutoWired just like you would with @bean.

Classes annotated with @Service are typically explicitly business Service layers, with a clear division from a business perspective.

18. @Component

There is no essential difference between @ Component and @Service. @Service still references @ Component inside.

The @Component annotation is used when the function is packaged as a component and expected to be managed by IOC when the business cannot be clearly divided or classified. @Component and @Service are divided into business functions only. Their essence is to “leave the life cycle of objects to IOC management”.

For example, the following example uses the @Component annotation

Source: the SRC/main/Java/com/springboot/codingstudty/configuration/CreateBean. Java

@Component
public class CreateBean implements ApplicationContextAware {
    / /...
}
Copy the code

19. @Repository

@repository is similar to @Controller, @Service, and @Component in that it hands objects over to IOC. The @Repository annotation is used on the interface of the persistence layer. This annotation is to hand over an implementation class of the interface to Spring to manage. With the @Repository annotation, you have the ability to turn native database exceptions into exceptions handled by Spring.

There are two places where this annotation is needed, in the persistence layer in normal Spring projects and on the interface when using JPA, and more often on the JPA interface in Spring Boot projects.

The JPA interface is used as follows:

/** * Description: Dao layer *@author ming
*/
@Repository
public interface UserDao extends JpaRepository<User.String>{
    //TODO
}
Copy the code

Sometimes you can get an implementation class for this interface without annotating @repository for several reasons:

  • The MapperScannerConfigurer bean is configured in the Spring configuration file, which scans the persistence layer interfaces to create implementation classes that spring can administer.
  • The @mapper annotation is used on the interface or the @Mapperscan annotation is used on the main class in SpringBoot. This annotation works the same as MapperScannerConfigurer.

For example, when using the SSM framework, @mapper is often injected into the Dao layer (this requires the introduction of MyBatis or MyBatisPlus dependencies).

20. @Autowired

@autoWired, mentioned several times above, is used for “new instances”. The annotated object can be called directly instead of manually new objects.

// Note that adding @autoWired equals new UserAction
@Autowired
UserAction userAction;
Copy the code

You can use @Resource in this way when there are multiple beans of the same type, as described below.

21. @Resource

Using @Resource is similar to @Autowired

@Resource(name = "userAction1")
UserAction userAction;
Copy the code

22. @Autowired+@Qualifier

@Autowired+@Qualifier

@Autowired
@Qualifier(value = "userAction1")
UserAction userAction;
Copy the code

23. @Value

@value is used to obtain the configuration information of application.properties. For example, application.properties has the following configuration:

(1) Application.properties:

server.port=8086

spring.datasource.url=jdbc:mysql://localhost:3309/db01
Copy the code

(2) Use @Value

Create the controller class ValueController

Source: the SRC/main/Java/com/springboot/codingstudty/controller/ValueController Java

@RestController
public class ValueController {
    @Value("${server.port}")
    public String port;
    public static String DATA_SOURCE_URL;

    / * * *@valueTo assign a value to a static variable, add the set method * and the method name and parameter can be arbitrary. *@param val
    */

    @Value ("${spring.datasource.url}")
    public void setDataSourceUrl(String val){
        DATA_SOURCE_URL = val;
    }

    @GetMapping("val")
    public String getVal(a){
        return "Port number ="+ port+",DataSource URL ="+DATA_SOURCE_URL; }}Copy the code

Notice how @ Value assigns a value to a static variable.

Running results: