Home > Java > javaTutorial > The 7 most commonly used annotations in Spring, the most powerful organization in history!

The 7 most commonly used annotations in Spring, the most powerful organization in history!

Release: 2023-07-26 16:38:25
forward
1058 people have browsed it
With the update and iteration of technology, Java5.0 began to support annotations. As the leading framework in Java, spring has slowly begun to abandon xml configuration since it was updated to version 2.5, and more annotations are used to control the spring framework.
There are so many annotations in spring that you may not be able to use them even if you have been working on Java for many years. Here is a summary of the 7 most commonly used annotations by type.


1

Core Notes

@Required
This annotation is used on the setter method of the bean. Indicates that this attribute is required and must be injected during the configuration phase, otherwise BeanInitializationExcepion will be thrown.
@Autowired
This annotation is used on the field, setter method and constructor method of the bean to explicitly declare dependencies. Autowiring based on type.
When you use this annotation on a field and use attributes to pass values, Spring will automatically assign the value to the field. This annotation can also be used for private properties (not recommended), as follows.
@Componentpublic class User {    @Autowired    private Address address;}
Copy after login
The most common use is to use this annotation on the setter, so that custom code can be added to the setter method. As follows:
<br/>
Copy after login
Copy after login
Copy after login
@Component
public class User {
   private Address address;
    
   @AutoWired
   public setAddress(Address address) {
      // custom code
      this.address=address;
   }
}
Copy after login
When using this annotation on the constructor, one thing to note is that only one constructor in a class is allowed to use this annotation. .
<br/>
In addition, after Spring 4.3, if a class has only one constructor, even if this annotation is not used , then Spring will also automatically inject related beans. As follows:
<br/>
Copy after login
Copy after login
Copy after login
@Component
public class User {
    private Address address;
    
    public User(Address address) {
       this.address=address;
     }
}

<bean id="user" class="xx.User"/>
Copy after login
@Qualifier<br/>
此注解是和@Autowired一起使用的。使用此注解可以让你对注入的过程有更多的控制。
@Qualifier可以被用在单个构造器或者方法的参数上。当上下文有几个相同类型的bean, 使用@Autowired则无法区分要绑定的bean,此时可以使用@Qualifier来指定名称。
@Component
public class User {
    @Autowired
    @Qualifier("address1")
    private Address address;
    ...
}
Copy after login
@Configuration
Copy after login
此注解用在class上来定义bean。其作用和xml配置文件相同,表示此bean是一个Spring配置。此外,此类可以使用@Bean注解来初始化定义bean。
@Configuartion
public class SpringCoreConfig {
    @Bean
    public AdminUser adminUser() {
        AdminUser adminUser = new AdminUser();
        return adminUser;
    }
}
Copy after login
@ComponentScan
此注解一般和@Configuration注解一起使用,指定Spring扫描注解的package。如果没有指定包,那么默认会扫描此配置类所在的package。
@Lazy
此注解使用在Spring的组件类上。默认的,Spring中Bean的依赖一开始就被创建和配置。如果想要延迟初始化一个bean,那么可以在此类上使用Lazy注解,表示此bean只有在第一次被使用的时候才会被创建和初始化。
此注解也可以使用在被@Configuration注解的类上,表示其中所有被@Bean注解的方法都会延迟初始化。
@Value
此注解使用在字段、构造器参数和方法参数上。@Value可以指定属性取值的表达式,支持通过#{}使用SpringEL来取值,也支持使用${}来将属性来源中(Properties文件、本地环境变量、系统属性等)的值注入到bean的属性中。
推荐大家看下:Java 必须掌握的 12 种 Spring 常用注解,这篇也是必看了。<br/>
此注解值的注入发生在AutowiredAnnotationBeanPostProcessor类中。


2

Spring MVC和REST注解

@Controller
此注解使用在class上声明此类是一个Spring controller,是@Component注解的一种具体形式。<br/>
@RequestMapping
此注解可以用在class和method上,用来映射web请求到某一个handler类或者handler方法上。
当此注解用在Class上时,就创造了一个基础url,其所有的方法上的@RequestMapping都是在此url之上的。
可以使用其method属性来限制请求匹配的http method。
@Controller
@RequestMapping("/users")
public class UserController {
    @RequestMapping(method = RequestMethod.GET)
    public String getUserList() {
        return "users";
    }
}
Copy after login
这篇也推荐大家看下:Spring MVC常用注解。此外,Spring4.3之后引入了一系列@RequestMapping的变种。如下:
Copy after login
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping

分别对应了相应method的RequestMapping配置。

关注微信公众号:Java技术栈,在后台回复:spring,可以获取我整理的 N 篇最新 Spring 教程,都是干货。
@CookieValue
此注解用在@RequestMapping声明的方法的参数上,可以把HTTP cookie中相应名称的cookie绑定上去。
@ReuestMapping("/cookieValue")
      public void getCookieValue(@CookieValue("JSESSIONID") String cookie){
}
Copy after login
cookie即http请求中name为JSESSIONID的cookie值。
@CrossOrigin
此注解用在class和method上用来支持跨域请求,是Spring 4.2后引入的。
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/users")
public class AccountController {
    @CrossOrigin(origins = "http://xx.com")
    @RequestMapping("/login")
    public Result userLogin() {
        // ...
    }
}
Copy after login
@ExceptionHandler<br/>
此注解使用在方法级别,声明对Exception的处理逻辑。可以指定目标Exception。
@InitBinder
此注解使用在方法上,声明对WebDataBinder的初始化(绑定请求参数到JavaBean上的DataBinder)。在controller上使用此注解可以自定义请求参数的绑定。
@MatrixVariable
此注解使用在请求handler方法的参数上,Spring可以注入matrix url中相关的值。这里的矩阵变量可以出现在url中的任何地方,变量之间用;分隔。如下:
// GET /pets/42;q=11;r=22
@RequestMapping(value = "/pets/{petId}")
public void findPet(@PathVariable String petId, @MatrixVariable int q) {
    // petId == 42
    // q == 11
}
Copy after login
需要注意的是默认Spring mvc是不支持矩阵变量的,需要开启。
<mvc:annotation-driven enable-matrix-variables="true" />
Copy after login
注解配置则需要如下开启:
<br/>
Copy after login
Copy after login
Copy after login
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
 
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setRemoveSemicolonContent(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}
Copy after login
@PathVariable<br/>此注解使用在请求handler方法的参数上。@RequestMapping可以定义动态路径,如:
@RequestMapping("/users/{uid}")
Copy after login
可以使用@PathVariable将路径中的参数绑定到请求方法参数上。
<br/>
@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid") String uid){
}
Copy after login
关注微信公众号:Java技术栈,在后台回复:spring,可以获取我整理的 N 篇最新 Spring 系列程,都是干货。
<br/>
@RequestAttribute
<br/>
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 parameters of the request handler method to change the Body of the http request The map is bound 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 add the http request header The value is bound to the parameter.
@RequestParam
This annotation is used on the parameters of the request handler method and is used to change the http request parameters. Values ​​are bound to parameters.
@RequestPart
This annotation is used on the parameters of the request handler method, used to transfer files and the like multipart is bound to the parameter.
@ResponseBody
This annotation is used on the request handler method. Similar to @RequestBody, it is used to directly output the return object of the method into the http response.
@ResponseStatus
This annotation is used on methods and exception classes to declare what this method or exception class returns http status code. You can use this annotation on the Controller so that all @RequestMapping will inherit.
@ControllerAdvice
This annotation is used on class. As mentioned earlier, you can declare an ExceptionMethod for each controller.
Here you can use @ControllerAdvice to declare a class to uniformly handle all @RequestMapping methods with @ExceptionHandler, @InitBinder and @ModelAttribute.
@RestController
This annotation is used on the class to declare that this controller returns not a view but a Domain objects. It also introduces two annotations @Controller and @ResponseBody.
@RestControllerAdvice
This annotation is used on class and introduces two annotations @ControllerAdvice and @ResponseBody .
@SessionAttribute
This annotation is used on the parameters of the method to bind the attributes in the session. to parameters.
@SessionAttributes
This annotation is used at the type level and is used to store JavaBean objects into the session. Generally used together with @ModelAttribute annotation.如下:
@ModelAttribute("user")

public PUser getUser() {}

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

public class UserController {}
Copy after login


3

Spring Boot注解

@EnableAutoConfiguration
此注解通常被用在主应用class上,告诉Spring Boot自动基于当前包添加Bean、对bean的属性进行设置等。
@SpringBootApplication
此注解用在Spring Boot项目的应用主类上(此类需要在base package中)。
使用了此注解的类首先会让Spring Boot启动对base package以及其sub-pacakage下的类进行component scan。这篇整理的也非常全:Spring Boot 最核心的 25 个注解建议大家看下。
此注解同时添加了以下几个注解:
@Configuration
@EnableAutoConfiguration
@ComponentScan


4

Stereotype注解

@Component
This annotation is used on the class to declare a Spring component (Bean) and add it to application context.
@Controller
As mentioned before
@Service
This annotation is used in class above, declare that this class is a service class that performs business logic, calculations, calls internal APIs, 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 a DAO role.
This annotation has the feature 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.
<br/>


#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 metadata that will be consumed by some runtime infrastructure.


6

任务执行、调度注解

@Scheduled
此注解使用在方法上,声明此方法被定时调度。使用了此注解的方法返回类型需要是Void,并且不能接受任何参数。
@Scheduled(fixedDelay=1000)
public void schedule() {

}

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

}
Copy after login
第二个与第一个不同之处在于其不会等待上一次的任务执行结束。
@Async
此注解使用在方法上,声明此方法会在一个单独的线程中执行。不同于Scheduled注解,此注解可以接受参数。
使用此注解的方法的返回类型可以是Void也可是返回值。但是返回值的类型必须是一个Future。


7

测试注解

@ContextConfiguration
此注解使用在Class上,声明测试使用的配置文件,此外,也可以指定加载上下文的类。
此注解一般需要搭配SpringJUnit4ClassRunner使用。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringCoreConfig.class)
public class UserServiceTest {

}
Copy after login

The above is the detailed content of The 7 most commonly used annotations in Spring, the most powerful organization in history!. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:Java学习指南
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template