preface

Anyone who has used Spring knows that spring can do a lot of things with simple annotations, but how does this work and how does it apply to our own code? Next, let’s start the journey of annotations together.

1. @Controller

Identifies a class that is the Spring MVC Controller handler used to create objects that handle HTTP requests.

@Controller public class TestController { @RequestMapping("/test") public String test(Map<String,Object> map){ return "hello"; }}Copy the code

2. @Component, @repository, @service, and @controller have the same functions

The difference between: If a Web application uses a classic three-tier hierarchy, it is best to annotate the classes in the persistence layer with @Repository, @Service, and @Controller, respectively, while annotating the more neutral classes with @Component.

It is used to assemble beans, primarily to annotate business layer components, and to manage the class by adding annotations to Spring.

@Service public interface UserService { User login(String username,String password); } // The Spring container will fail to inject annotations when they are written to the interface. // Annotations written on classes will not fail injection. @Service public class UserServiceImpl implements UserService{ @Autowired private UserMapper userMapper; } @Controller @RequestMapping("user") public class UserController { @Autowired private UserService userService }Copy the code

3. @Autowired

Used to assemble beans, either on fields or methods. The dependent object must exist by default. To allow null values, you can set its required property to false, for example: @autowired (required=false)

4. @RequestMapping

Class definition: Provides preliminary request mapping information relative to the WEB application root directory. Method: Provides further breakdown mapping information relative to the URL at the class definition. In plain English, this method and HTML page can be accessed by visiting localhost:8080/user.html on (for example, “user”) web sites.

5. @RequestParam

Used to map request parameter area data to function processing method parameters such as:

public Resp test(@RequestParam Integer id){
        return Resp.success(customerInfoService.fetch(id));
}

Copy the code

This id is used to receive the value of the parameter id passed from the interface, or if the parameter name passed from the interface is different from the value you received:

public Resp test(@RequestParam(value="userId") Integer id){
    return Resp.success(customerInfoService.fetch(id));
}

Copy the code

UserId is the parameter passed by the interface, and ID is the parameter name mapped to the userId.

6. @ModelAttribute

There are three kinds of use places:

  1. Tags on methods.

Tags on methods are executed before each @requestMapping method, and if there is a return value, the return value is automatically > added to ModelMap.

A. On methods that return: When ModelAttribute is set to value, the value returned by the method is stored in Model with the value as the key and the value received by the parameter as the value. The final equivalent is model.addattribute (” user_name “, name); If @modelAttribute does not have a custom value, it is equivalent to model.addattribute (” name “, name);

1@ModelAttribute(value="user_name") 2 public String before2(@RequestParam(required = false) String name, {3 system.out.println (" enter 2: "+ name); 4 return name; 5}Copy the code

B. On methods that do not return: manual model.add method is required

1 @ModelAttribute 2 public void before(@RequestParam(required = false) Integer age, Model model) { 3 model.addAttribute("age", age); 4 system.out. println(" enter 1: "+ age); 5}Copy the code

We create a request method under the current class:

1@RequestMapping(value="/mod") 2 public Resp mod( 3 @RequestParam(required = false) String name, 4 @requestParam (Required = false) Integer age, 5 Model Model){6 system.out.println (" enter mod"); 7 system.out. println(" name="+name+"; age="+age+"}"); 8 system.out. println("model :"+model); 9 return Resp.success("1"); 10}Copy the code

Enter access address in your browser and add parameters: http://localhost:8081/api/test/mod? Name = I am small dish &age=12

The final output is as follows:

1 went into 1:40, 2 went into 2: I am small dish 3 went into mod 4 parameter accepted value {name= I am small dish; {age=40, user_name= 1}Copy the code
  1. Marks the parameters of the method.

Marking the parameters of the method injects the parameters passed by the client into the specified object by name, and the object is automatically added to ModelMap for easy use by the View layer. We add a method to the above class as follows

1@RequestMapping(value="/mod2") 2 public Resp mod2(@ModelAttribute("user_name") String user_name, 3 @ModelAttribute("name") String name, 4 @modelAttribute ("age") Integer age,Model Model){5 system.out.println (" enter mod2"); 6 System.out.println("user_name:"+user_name); 7 System. Out. Println (" name: "+ name); 8 System.out.println("age:"+age); 9 System.out.println("model:"+model); 10 return Resp.success("1"); 11}Copy the code

Enter access address in your browser and add parameters: http://localhost:8081/api/test/mod2? Name = I am a small dish &age=12

Mod2 4user_name: I am small dish 5name: I am small dish 6age:40 7model:{user_name= I am small dish,Copy the code

org.springframework.validation.BindingResult.user_name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, name= org.springframework.validation.BindingResult.name=org.springframework.validation.BeanPropertyBindingResult: 0 errors, age=40, org.springframework.validation.BindingResult.age=org.springframework.validation.BeanPropertyBindingResult: 0 errors} As you can see from the results, the @modelAttribute annotation used in method parameters is actually a way of taking parameters and automatically putting them into Model objects for easy use.

7. @Cacheable

Used to mark cached queries. Can be used in a method or class to indicate that the method is cache-enabled when the tag is on a method and that all the methods in that class are cache-enabled. The list of parameters

@cacheable (value="UserCache") @accountCache Public Account getUserAge(int ID) {@cacheable (value="UserCache") Int age=getUser(id); return age; }Copy the code

8. @CacheEvict

The method used to mark the cache to be emptied. When this method is called, the cache is emptied. @cacheevict (value= “UserCache”) parameter list

9. @Resource

@Resource is just like @AutoWired except that @AutoWired is automatically injected by byType, whereas @Resource is automatically injected by byName by default.

The @Resource attribute has two important attributes: name and type. Spring interprets the @Resource attribute name to the bean name, and the type attribute to the bean type. So if the name attribute is used, the byName auto-injection policy is used, and if the Type attribute is used, the byType auto-injection policy is used. If neither name nor type attributes are specified, the byName automatic injection policy is used through reflection.

@resource assembly order: If both name and type are specified, a unique matching bean will be found from the Spring context and assembled. If no matching bean is found, an exception will be thrown

If type is specified, an exception will be thrown if a unique bean whose type matches is found in the context and assembly is performed

If neither name nor type is specified, byName is automatically used for assembly. If there is no match, the system backs up to a primitive type for matching. If there is a match, automatic assembly is performed.

10. @PostConstruct

Used to indicate that the method is executed at project startup time. Void () decorates a non-static void() method that is executed when the Spring container starts, and is used for loading global configurations, data dictionaries, and the like

Methods decorated with @postconstruct run when the server loads the Servlet and are executed by the server only once. PostConstruct is executed after the constructor and before the init() method. The PreDestroy () method is executed after the destroy() method executes

11. @PreDestroy

The @predestroy modified method runs when the server uninstalls the Servlet and is called only once by the server, similar to the destroy() method of the Servlet. Methods modified by @predestroy run after destroy(), before the Servlet is completely uninstalled

12.@Repository

Used to annotate data access components, known as DAO components

13.@Component

This annotation refers to components in general, and can be used to annotate components when they are difficult to categorize

14.@Scope

To configure the scope of the Spring bean, which identifies the scope of the bean. The default value is singleton

Prototype: a new instance is generated each time a Bean is fetched

Request: Request indicates that a new bean is generated for each HTTP request and is valid only in the current HTTP Request

Session: The session scope means that a new bean is generated for each HTTP request and is valid only for the current HTTP session

Global Session: Used only in Portal applications. Create a Bean instance for each Global HTTP session. **

15. @SessionAttributes

By default, Spring MVC stores the data in the model into the Request domain. When a request ends, the data is invalidated. If you want to use it across pages. So you need to use sessions. The @sessionAttributes annotation causes a copy of the data in the model to be stored in the session domain

Parameter: names: This is an array of strings. It should contain the name of the data to be stored in the session. Types: Stores parameters of the corresponding type in the model into the session based on the specified parameter type value: the same as names.

@Controller @SessionAttributes(value={"names"},types={Integer.class}) public class ScopeService { @RequestMapping("/testSession") public String test(Map<String,Object> map){ map.put("names", Arrays.asList("a","b","c")); map.put("age", 12); return "hello"; }}Copy the code

16. @Required

Applies to the setter method for bean properties and indicates that the affected bean properties must be populated at configuration time in the XML configuration file. Otherwise, the container will be thrown a BeanInitializationException anomalies.

17. @Qualifier

When you create multiple beans of the same type and want to assemble only one of them with a property, you can use the @Qualifier annotation and the @AutoWired annotation to eliminate confusion by specifying which actual bean will be assembled.

18.@PathVariable

@pathVariable can be used to map placeholders in the URL to parameters of the target method

@RequestMapping("/testPathVariable/{id}")
public String testPathVariable(@PathVariable("id") Integer id){
    System.out.println("testPathVariable:"+id);
    return SUCCESS;
}

Copy the code

1.@RestController: All methods of the controller defined return the @responseBody method by default, converting the return value to JSON. Note: @ RestController = @ Controller + @ ResponseBody

2. @ ResponseBody: So if you set @responseBody and your controller method returns a JavaBean object then that JavaBean is converted to a JSON object and sent to the browser in the body of the response and the ContentType of the response is Application/JSON, Indicates JSON data 3.@GetMapping: processes GET requests 4.@PostMapping: processes POST requests

Note:@getMapping (“/get_test”) is equivalent to @requestMapping (value = “/get_test”,method = requestmethod.get) to simplify the RequestMapper Designed to handle Get requests

19.@Data

Add the @data annotation to the front of the class name, and Lombok (a plug-in that saves entity class code) adds getters, setters, and toString methods to the class during compilation. Add full attribute note equals, hashCode methods. Save entity class code, don’t write get, set… Methods)

Lombok does automatically generate some of the above methods after testing.

The last

You can leave a comment below to discuss what you don’t understand. You can also pay attention to my private letter and ask me. I will answer it after I see it. Also welcome everyone to pay attention to my public account: the future is bright, immediately gold nine silver ten job-hunting interview season, sorted out more than 1000 nearly more than 500 pages of PDF document Java interview questions in it, to help you realize your dream BAT! Articles will be updated in it, and sorted data will be placed in it. Thank you for watching, think the article is helpful to you remember to pay attention to me a thumb-up support!