Common annotations in Spring, which ones do you use?

Since Java 5.0, Java has started to support annotations. As the leading framework in the Java ecosystem, Spring has also supported annotations since version 2.5. Compared to using xml to configure the Spring framework, using annotations provides more control over the Spring framework.

Now more and more projects are using annotations for related configuration, but Spring has a lot of annotations, and I believe many of them have never been used. This article will try to give a comprehensive overview of the commonly used annotations in Spring.

1. Core annotations

@Required

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

@Autowired

This annotation is used on bean fields, setter methods, and constructors to explicitly declare dependencies. Autowiring according to type.

When using this annotation on a field, and using an attribute 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.

1
2
3
4
5
@Component
public class User {
    @Autowired                               
    private Address address;                   
}

The most common usage is to use this annotation on a setter so that custom code can be added to the setter method. as follows:

1
2
3
4
5
6
7
8
9
10
@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 in a class is allowed to use this annotation. 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:

1
2
3
4
5
6
7
8
9
10
@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 a single constructor or method parameter. When the context has several beans of the same type, using @Autowired cannot distinguish the bean to be bound. In this case, you can use @Qualifier to specify the name.

1
2
3
4
5
6
7
@Component
public class User {
    @Autowired
    @Qualifier("address1")
    private Address address;
    ...
}

@Configuration

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

1
2
3
4
5
6
7
8
@Configuartion
public class SpringCoreConfig {
    @Bean
    public AdminUser adminUser() {
        AdminUser adminUser = new AdminUser();
        return adminUser;
    }
}

@ComponentScan

This annotation is generally used in conjunction with the @Configuration annotation to specify the package that Spring scans for the annotation. 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's component classes. By default, Bean dependencies in Spring are created and configured from the start. If you want to lazily initialize a bean, you can use the Lazy annotation on this class to indicate that the bean will only be created and initialized the first time it is used. This annotation can also be used on classes annotated with @Configuration, indicating that all methods annotated with @Bean will be initialized lazily.

@Value

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

2. Stereotype annotation

@Component

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

@Controller

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

@Service

This annotation is used on a class to declare that this class is a service class that performs business logic, calculations, calls internal APIs, etc. It is a concrete form of the @Component annotation.

@Repository

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

This annotation has the characteristics of automatic translation. For example, when this component throws an exception, there will be a handler to handle the exception without using a try-catch block.

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 bean properties, and so on.

@SpringBootApplication

This annotation is used on the application main class of the Spring Boot project (this class needs to be in the base package). Classes using this annotation will first make Spring Boot start component scan for the base package and the classes under its sub-pacakage.

This annotation also adds the following annotations:

  • @Configuration
  • @EnableAutoConfiguration
  • @ComponentScan

4. Spring MVC and REST annotations

@Controller

This annotation has been mentioned above.

@RequestMapping

This annotation can be used on classes and methods to map web requests to a handler class or handler method. When this annotation is used on a Class, a base url is created, and all @RequestMappings on its methods are based on this url.

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

1
2
3
4
5
6
7
8
@Controller
@RequestMapping("/users")
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUserList() {
        return "users";
    }
}

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

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @PatchMapping
  • @DeleteMapping

They correspond 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.

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

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

Recommend a Java advanced technology advanced group to help you become an excellent architect:

Group number: 688583154, you can get free Java architect learning materials, which are the most mainstream technologies at present, explaining the structural structure of the framework, the underlying principles, as well as the knowledge points of source code analysis and performance optimization. If you need it, you want to become an architect. can be added.

 

@CrossOrigin

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

1
2
3
4
5
6
7
8
9
10
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
    @CrossOrigin(origins = "http://xx.com")
    @RequestMapping("/login")
    public Result userLogin() {
        // ...
    }
}

@ExceptionHandler

此注解使用在方法级别,声明对Exception的处理逻辑。可以指定目标Exception。

@InitBinder

此注解使用在方法上,声明对WebDataBinder的初始化(绑定请求参数到JavaBean上的DataBinder)。在controller上使用此注解可以自定义请求参数的绑定。

@MatrixVariable

此注解使用在请求handler方法的参数上,Spring可以注入matrix url中相关的值。这里的矩阵变量可以出现在url中的任何地方,变量之间用;分隔。如下:

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

需要注意的是默认Spring mvc是不支持矩阵变量的,需要开启。

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

注解配置则需要如下开启:

1
2
3
4
5
6
7
8
9
10
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

@PathVariable

此注解使用在请求handler方法的参数上。@RequestMapping可以定义动态路径,如:

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

可以使用@PathVariable将路径中的参数绑定到请求方法参数上。

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

@RequestAttribute

此注解用在请求handler方法的参数上,用于将web请求中的属性(request attributes,是服务器放入的属性值)绑定到方法参数上。

@RequestBody

此注解用在请求handler方法的参数上,用于将http请求的Body映射绑定到此参数上。HttpMessageConverter负责将对象转换为http请求。

@RequestHeader

此注解用在请求handler方法的参数上,用于将http请求头部的值绑定到参数上。

@RequestParam

此注解用在请求handler方法的参数上,用于将http请求参数的值绑定到参数上。

@RequestPart

此注解用在请求handler方法的参数上,用于将文件之类的multipart绑定到参数上。

@ResponseBody

此注解用在请求handler方法上。和@RequestBody作用类似,用于将方法的返回对象直接输出到http响应中。

@ResponseStatus

此注解用于方法和exception类上,声明此方法或者异常类返回的http状态码。可以在Controller上使用此注解,这样所有的@RequestMapping都会继承。

@ControllerAdvice

此注解用于class上。前面说过可以对每一个controller声明一个ExceptionMethod。这里可以使用@ControllerAdvice来声明一个类来统一对所有@RequestMapping方法来做@ExceptionHandler、@InitBinder以及@ModelAttribute处理。

@RestController

此注解用于class上,声明此controller返回的不是一个视图而是一个领域对象。其同时引入了@Controller和@ResponseBody两个注解。

@RestControllerAdvice

此注解用于class上,同时引入了@ControllerAdvice和@ResponseBody两个注解。

@SessionAttribute

此注解用于方法的参数上,用于将session中的属性绑定到参数。

@SessionAttributes

此注解用于type级别,用于将JavaBean对象存储到session中。一般和@ModelAttribute注解一起使用。如下:

1
2
3
4
5
6
7
8
9
10
11
@ModelAttribute("user")
public PUser getUser() {}
// controller和上面的代码在同一controller中
@Controller
@SeesionAttributes(value = "user", types = {
    User.class
})
public class UserController {}

五. 数据访问注解

@Transactional

此注解使用在接口定义、接口中的方法、类定义或者类中的public方法上。需要注意的是此注解并不激活事务行为,它仅仅是一个元数据,会被一些运行时基础设施来消费。

六. 任务执行、调度注解

@Scheduled

此注解使用在方法上,声明此方法被定时调度。使用了此注解的方法返回类型需要是Void,并且不能接受任何参数。

1
2
3
4
5
6
7
8
9
@Scheduled(fixedDelay=1000)
public void schedule() {
}
@Scheduled(fixedRate=1000)
public void schedulg() { 
}

第二个与第一个不同之处在于其不会等待上一次的任务执行结束。

推荐一个Java高级技术进阶群,助你成为一名优秀的架构师:

群号:688583154,可获取免费的Java架构师学习资料,都是目前最主流的技术,讲解框架的结构构造,底层原理,还有源码分析,性能优化这些知识点,有需要,想成为架构师的可以加一下。

@Async

此注解使用在方法上,声明此方法会在一个单独的线程中执行。不同于Scheduled注解,此注解可以接受参数。

使用此注解的方法的返回类型可以是Void也可是返回值。但是返回值的类型必须是一个Future。

七. 测试注解

@ContextConfiguration

此注解使用在Class上,声明测试使用的配置文件,此外,也可以指定加载上下文的类。

此注解一般需要搭配SpringJUnit4ClassRunner使用。

1
2
3
4
5
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325397482&siteId=291194637