The 7 most commonly used annotations in Spring are recommended for collection!

With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in java, spring, since the update of version 2.5, has gradually abandoned the xml configuration and used more annotations to control the spring framework.

However, there are so many annotations in spring, and it may not be used for many years in java. Here is a summary of the 7 most commonly used annotations by type.

1.  Core annotations

@Required

This annotation is used on the bean's setter method. Indicates that this property is required and must be injected during the configuration phase, otherwise a BeanInitializationException will be thrown.

@Autowired

This annotation is used on the bean's field, setter method, and constructor to explicitly declare dependencies. Autowiring according to type.

When using this annotation on a field and using a property to pass a value, Spring will automatically assign the value to the field. You can also use this annotation for private properties (not recommended), as follows.

@Component
public class User {
    @Autowired
    private Address address;
}

The most common usage is to use this annotation on the setter, so that you can add custom code in the setter method. as follows:

@Component
public class User {
   private Address address;
    
   @AutoWired
   public setAddress(Address address) {
      // custom code
      this.address=address;
   }
}

When using this annotation on a constructor, one thing to note is that only one constructor is allowed to use this annotation in a class.

In addition, after Spring 4.3, if a class has only one constructor, even if this annotation is not used, Spring will automatically inject related beans. as follows:

@Component
public class User {
    private Address address;
    
    public User(Address address) {
       this.address=address;
     }
}

<bean id="user" class="xx.User"/>

@Qualifier

This annotation is used with @Autowired. Using this annotation gives you more control over the injection process.

@Qualifier can be used on individual constructor or method parameters. When the context has several beans of the same type, it is impossible to distinguish the bean to be bound using @Autowired. At this time, @Qualifier can be used to specify the name.

@Component
public class User {
    @Autowired
    @Qualifier("address1")
    private Address address;
    ...
}

@Configuration

This annotation is used on the class to define the bean. Its function is the same as that of the xml configuration file, indicating that this bean is a Spring configuration. Additionally, this class can use the @Bean annotation to initially define beans.

@Configuartion
public class SpringCoreConfig {
    @Bean
    public AdminUser adminUser() {
        AdminUser adminUser = new AdminUser();
        return adminUser;
    }
}

@ComponentScan

This annotation is generally used together with the @Configuration annotation to specify the package for Spring scanning annotations. If no package is specified, the package where this configuration class is located will be scanned by default.

@Lazy

This annotation is used on Spring component classes. By default, the bean's dependencies in Spring are created and configured from the start. If you want to delay the initialization of a bean, you can use the Lazy annotation on this class, indicating that the bean will only be created and initialized when it is used for the first time.

This annotation can also be used on classes annotated by @Configuration, indicating that all methods annotated by @Bean will be initialized lazily.

@Value

This annotation is used on fields, constructor parameters and method parameters. @Value can specify the expression of the attribute value, supports the use of SpringEL to obtain the value through #{}, and also supports the use of ${} to inject the value of the attribute source (Properties file, local environment variable, system property, etc.) into the bean in the properties.

The injection of this annotation value occurs in the AutowiredAnnotationBeanPostProcessor class.

2. Spring MVC and REST annotations

@Controller

This annotation is used to declare that this class is a Spring controller on the class, which is a concrete form of @Component annotation.

@RequestMapping

This annotation can be used on class and method to map web requests to a certain handler class or handler method.

When this annotation is used on Class, a base url is created, and @RequestMapping on all its methods are above this url.

You can use its method attribute to limit the http method that the request matches.

@Controller
@RequestMapping("/users")
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUserList() {
        return "users";
    }
}

In addition, a series of @RequestMapping variants were introduced after Spring 4.3. as follows:

@GetMapping

@PostMapping

@PutMapping

@PatchMapping

@DeleteMapping

Corresponding to the RequestMapping configuration of the corresponding method.

@CookieValue

This annotation is used on the parameters of the method declared by @RequestMapping to bind the cookie with the corresponding name in the HTTP cookie.

@ReuestMapping("/cookieValue")
      public void getCookieValue(@CookieValue("JSESSIONID") String cookie){
}

The cookie is the cookie value whose name is JSESSIONID in the http request.

@CrossOrigin

This annotation is used on classes and methods to support cross-domain requests, and was introduced after Spring 4.2.

@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
    @CrossOrigin(origins = "http://xx.com")
    @RequestMapping("/login")
    public Result userLogin() {
        // ...
    }
}

@ExceptionHandler

This annotation is used at the method level to declare the processing logic for Exception. The target Exception can be specified.

@InitBinder

This annotation is used on the method to declare the initialization of WebDataBinder (binding request parameters to DataBinder on JavaBean). Use this annotation on the controller to customize the binding of request parameters.

@MatrixVariable

This annotation is used on the parameters of the request handler method, and Spring can inject the relevant values ​​in the matrix url. The matrix variables here can appear anywhere in the url, and the variables are separated by ;. as follows:

// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
    // petId == 42
    // q == 11
}

It should be noted that the default Spring mvc does not support matrix variables and needs to be enabled.

<mvc:annotation-driven enable-matrix-variables="true" />

Annotation configuration needs to be enabled as follows:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

@PathVariable
This annotation is used on the parameters of the request handler method. @RequestMapping can define dynamic paths, such as:

@RequestMapping("/users/{uid}")

You can use @PathVariable to bind parameters in the path to request method parameters.

@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid") String uid){
}

@RequestAttribute

This annotation is used on the parameters of the request handler method to bind the attributes in the web request (request attributes, which are the attribute values ​​​​put by the server) to the method parameters.

@RequestBody

This annotation is used on the parameter of the request handler method to bind the Body mapping of the http request to this parameter. HttpMessageConverter is responsible for converting objects into http requests.

@RequestHeader

This annotation is used on the parameters of the request handler method to bind the value of the HTTP request header to the parameters.

@RequestParam

This annotation is used on the parameters of the request handler method to bind the value of the http request parameter to the parameter.

@RequestPart

This annotation is used on the parameters of the request handler method to bind multiparts such as files to the parameters.

@ResponseBody

This annotation is used on the request handler method. Similar to @RequestBody, it is used to output the return object of the method directly into the http response.

@ResponseStatus

This annotation is used on methods and exception classes to declare the HTTP status code returned by this method or exception class. This annotation can be used on Controller so that all @RequestMapping will inherit.

@ControllerAdvice

This annotation is used on class. As mentioned earlier, an ExceptionMethod can be declared for each controller.

Here you can use @ControllerAdvice to declare a class to uniformly handle @ExceptionHandler, @InitBinder and @ModelAttribute for all @RequestMapping methods.

@RestController

This annotation is used on the class to declare that what the controller returns is not a view but a domain object. It also introduces two annotations @Controller and @ResponseBody.

@RestControllerAdvice

This annotation is used on the class and introduces @ControllerAdvice and @ResponseBody two annotations at the same time.

@SessionAttribute

This annotation is used on the parameters of the method to bind the attributes in the session to the parameters.

@SessionAttributes

This annotation is used at the type level to store JavaBean objects in the session. Generally used with @ModelAttribute annotation. as follows:

@ModelAttribute("user")

public PUser getUser() {}

// controller和上面的代码在同一controller中
@Controller
@SeesionAttributes(value = "user", types = {
    User.class
})

public class UserController {}

3.  Spring Boot annotations

@EnableAutoConfiguration

This annotation is usually used on the main application class to tell Spring Boot to automatically add beans based on the current package, set the properties of the beans, and so on.

@SpringBootApplication

This annotation is used on the main application class of the Spring Boot project (this class needs to be in the base package).

The class using this annotation will first let Spring Boot start the component scan of the base package and the classes under its sub-package.

This annotation also adds the following annotations:

@Configuration

@EnableAutoConfiguration

@ComponentScan

4.  Stereotype annotations

@Component

This annotation is used on the class to declare a Spring component (Bean) and add it to the application context.

@Controller

already mentioned

@Service

This annotation is used on the class, declaring that this class is a service class, performing business logic, calculation, calling internal api, etc. It is a specific form of @Component annotation.

@Repository

This class is used to declare this class on the class to access the database, generally as the role of DAO.

This annotation has the feature of automatic translation, for example: when this kind of component throws an exception, then there will be a handler to handle the exception, no need to use try-catch block.

5.  Data access annotations

@Transactional

This annotation is used on interface definitions, methods in interfaces, class definitions, or public methods in classes. It should be noted that this annotation does not activate transaction behavior, it is just a metadata, which will be consumed by some runtime infrastructure.

6.  Task execution, scheduling annotations

@Scheduled

This annotation is used on a method to declare that this method is scheduled regularly. The return type of the method using this annotation needs to be Void and cannot accept any parameters.

@Scheduled(fixedDelay=1000)
public void schedule() {

}

@Scheduled(fixedRate=1000)
public void schedulg() {

}

The second differs from the first in that it does not wait for the last task execution to end.

@Async

This annotation is used on a method to declare that this method will be executed in a separate thread. Unlike the Scheduled annotation, this annotation can accept parameters.

The return type of the method using this annotation can be Void or return value. But the type of the return value must be a Future.

7. Test annotations

@ContextConfiguration

This annotation is used on Class to declare the configuration file used by the test. In addition, it can also specify the class to load the context.

This annotation generally needs to be used with SpringJUnit4ClassRunner.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {

}

Well, that’s all for this article, welcome friends to leave a message in the background, tell me which Spring annotations you have used in the project!

 For more content, please pay attention to the official account [Programmer Style] to get more exciting content!

Guess you like

Origin blog.csdn.net/dreaming317/article/details/129866602