1. @Controller
  2. @ RestController:
  3. @Service
  4. @Autowired
  5. @RequestMapping
  6. @RequestParam
  7. @ModelAttribute
  8. @Cacheable
  9. @CacheEvict
  10. @Resource
  11. @PostConstruct
  12. @PreDestroy
  13. @Repository
  14. @Component
  15. @Scope
  16. @SessionAttributes
  17. @Required
  18. @Qualifier

@Controller

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

1@Controller

2public class TestController {

3        @RequestMapping("/test")

4        public String test(Map<String,Object> map){

5

6            return "hello";

7        }

8}

Copy the code

@RestController

If you replace @controller with @restController, you do not need to configure @responseBody again. The default value is json.

1@RestController

2public class TestController {

3        @RequestMapping("/test")

4        public String test(Map<String,Object> map){

5

6            return "hello";

7        }

8}

Copy the code

@Service

To annotate business layer components, you simply add an annotation to inject this class into the Spring configuration

@Autowired

To assemble a bean, you can write it either in a field or in a method. Dependent objects must exist by default. To allow null values, you can set its required attribute to false, for example: @autowired (Required =false)

@RequestMapping

Class definition: Provides preliminary request mapping information, relative to the root directory of the WEB application. Method: Provides further detailed mapping information, relative to the URL at the class definition.

Those who have used RequestMapping know that it has many functions, so I will talk about the detailed usage in the next article. Please follow the official account, so as not to miss it.

@RequestParam

Used to map request parameter area data to parameters of functional processing methods for example

1public Resp test(@RequestParam Integer id){

2        return Resp.success(customerInfoService.fetch(id));

3    }

Copy the code

This id is intended to receive the value of the parameter ID passed from the interface. If the parameter name passed from the interface is different from the one you received, it can also be as follows

1public Resp test(@RequestParam(value="course_id") Integer id){

2        return Resp.success(customerInfoService.fetch(id));

3    }

Copy the code

Where the course_id is the parameter passed by the interface, and the ID is the parameter name that maps the course_ID

@ModelAttribute

There are three places to use:

1. Mark on the method.

The tag is executed on the method before each @RequestMapping annotated method, and if there is a return value, it is automatically added to the ModelMap.

A. On methods with returns:

When ModelAttribute is set to value, the value returned by the method will be stored in the Model with this value as the key and the value received by the parameter as the value. 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, Model model) {

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

Let’s 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("Into the mod");

7        System.out.println("Parameter accepts value {name="+name+"; age="+age+"}");

8        System.out.println("Value passed by 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’m a side dish &age=12

The final output is as follows:

1It's going into 1:40

2Enter 2: I am a side dish

3Enter the mod

4The parameter accepts a value {name= I'm a side dish; age=12}

5{age=40, user_name= 0}

Copy the code

2. Mark the parameters of the method.

The tag on the method parameter injects the parameter passed by the client into the specified object by name, and the object is automatically added to the ModelMap for the View layer to use. Let’s 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’m a side dish &age=12

1It's going into 1:40

2Enter 2: I am a side dish

3Enter the mod2

4User_name: I am a side dish

5Name: I'm a side dish

6age:40

7Model :{user_name= 0; 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}

Copy the code

As you can see from the results, the @ModelAttribute annotation used in the method parameters is actually a way of taking the parameters and automatically putting them into the Model object for ease of use.

@Cacheable

Used to mark a cache query. Can be used in methods or classes,

When the tag is on a method it means that the method supports caching, and when the tag is on a class it means that all the methods of that class support caching.

The list of parameters

parameter explain example
value The name of the @ Cacheable (value = {” c1 “, “c2”}
key key @ Cacheable (value = “c1”, the key # id “) =”
condition conditions @ Cacheable (value = “c1”, condition # id = = “1”)

For example, @cacheable (value=”UserCache”) identifies that when the method marked with this annotation is called, the logic defaults to fetching the result from the cache. If there is no data in the cache, the user-written query logic is executed and the result is placed in the cache when the query succeeds. All caches are key-value, so key is the parameter (id) in the method, value is the result of the query, and the namespace UserCache is defined in spring*.xml.

1@Cacheable(value="UserCache")// A cache named accountCache is used

2public Account getUserAge(int id) {  

3     // Do not write the cache logic, directly follow the normal business logic,

4     // The cache is automatically entered through the section

5    int age=getUser(id);   

6     return age;   

7

Copy the code

@CacheEvict

Method used to mark that the cache is to be cleared. When this method is called, the cache will be cleared. @ CacheEvict UserCache (value = “”)

The list of parameters

parameter explain example
value The name of the @ CachEvict (value = {” c1 “, “c2”}
key key @ CachEvict (value = “c1”, the key # id “) =”
condition Cache condition, which can be null
allEntries Whether to clear all cache contents @ CachEvict (value = “c1”, allEntries = true)
beforeInvocation Whether to clear the method before it executes @ CachEvict (value = “c1”, beforeInvocation = true)

@Resource

@Resource does the same thing as @Autowired except that @Autowired automatically injects byType, and @Resource automatically injects byName.

The @Resource annotation has two important attributes, name and type. Spring resolves the name attribute of the @Resource annotation to the name of the bean and the Type attribute to the type of the bean. Therefore, if the name attribute is used, the automatic injection policy of byName is used, and if the type attribute is used, the automatic injection policy of byType is used. If neither the name nor the type attribute is specified, the byName auto-injection policy is used through the reflection mechanism.

@resource assembly sequence:

  1. If both name and type are specified, a unique matching bean is found from the Spring context for assembly, and an exception is thrown if not found
  2. If name is specified, the bean whose name (ID) matches is assembled from the context and an exception is thrown if it is not found
  3. If type is specified, a unique bean with a matching type is found from the context for assembly, and an exception is thrown if none or more are found
  4. If neither name nor type is specified, the assembly is automatically carried out in byName mode. If there is no match, it is matched back to a primitive type. If there is a match, it is automatically assembled.

@PostConstruct

This method is used to indicate that it is executed when the project is started. A non-static void() method that is executed when the Spring container starts and is used for global configuration, data dictionary, and so on

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

@PreDestroy

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

@Repository

Used to annotate the data access component, the DAO component

@Component

Generally refers to components, and we can use this annotation when components are difficult to classify

@Scope

Use to configure the scope of Spring beans, which identifies the bean’s scope. The default is a singleton

  1. Singleton: A pattern in which there is only one instance globally

  2. Prototype: This is the prototype pattern that creates a new instance of the Bean every time it is fetched

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

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

  5. Global Session: Only available in portal applications. Create a Bean instance for each global HTTP session.

@SessionAttributes

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

Parameters:

  1. Names: This is an array of strings. It should write the name of the data to be stored in the session.
  2. Types: specifies the type of parameters in the model to be stored in the session. 3. Value: Is the same as names.
 1@Controller

2@SessionAttributes(value={"names"},types={Integer.class})

3public class ScopeService {

4        @RequestMapping("/testSession")

5        public String test(Map<String,Object> map){

6            map.put("names", Arrays.asList("a"."b"."c"));

7            map.put("age".12);

8            return "hello";

9        }

10}

Copy the code

@Required

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

@Qualifier

When you create multiple beans of the same type and want to assemble only one of them with a property, in this case you can use the @Qualifier annotation and @Autowired annotation to eliminate confusion by specifying which real beans will be assembled