注解总结原创
注解本身没有功能的,就和 xml 一样。注解和 xml 都是一种元数据,元数据即解释数据的数据,这就是所谓配置。
# Spring相关注解
注解 | 解释 |
---|---|
@Controller | 组合注解(组合了@Component注解),应用在MVC层(控制层),DispatcherServlet会自动扫描注解了此注解的类,然后将web请求映射到注解了@RequestMapping的方法上。 |
@Service | 组合注解(组合了@Component注解),应用在service层(业务逻辑层) |
@Reponsitory | 组合注解(组合了@Component注解),应用在dao层(数据访问层) |
@Component | 表示一个带注释的类是一个“组件”,成为Spring管理的Bean。当使用基于注解的配置和类路径扫描时,这些类被视为自动检测的候选对象。同时@Component还是一个元注解。 |
@Autowired | Spring提供的工具(由Spring的依赖注入工具(BeanPostProcessor、BeanFactoryPostProcessor)自动注入。) |
@Resource | JSR-250提供的注解 |
@Inject | JSR-330提供的注解 |
@Configuration | 声明当前类是一个配置类(相当于一个Spring配置的xml文件) |
@ComponentScan | 自动扫描指定包下所有使用@Service,@Component,@Controller,@Repository的类并注册 |
@Bean | 注解在方法上,声明当前方法的返回值为一个Bean。返回的Bean对应的类中可以定义init()方法和destroy()方法,然后在@Bean(initMethod=”init”,destroyMethod=”destroy”)定义,在构造之后执行init,在销毁之前执行destroy。 |
@Aspect | 声明一个切面(就是说这是一个额外功能) |
@After | 后置建言(advice),在原方法前执行。 |
@Before | 前置建言(advice),在原方法后执行。 |
@Around | 环绕建言(advice),在原方法执行前执行,在原方法执行后再执行(@Around可以实现其他两种advice) |
@PointCut | 声明切点,即定义拦截规则,确定有哪些方法会被切入 |
@Transactional | 声明事务(一般默认配置即可满足要求,当然也可以自定义) |
@Cacheable | 声明数据缓存 |
@EnableAspectJAutoProxy | 开启Spring对AspectJ的支持 |
@Value | 值得注入。经常与Sping EL表达式语言一起使用,注入普通字符,系统属性,表达式运算结果,其他Bean的属性,文件内容,网址请求内容,配置文件属性值等等 |
@PropertySource | 指定文件地址。提供了一种方便的、声明性的机制,用于向Spring的环境添加PropertySource。与@configuration类一起使用。 |
@PostConstruct | 标注在方法上,该方法在构造函数执行完成之后执行。 |
@PreDestroy | 标注在方法上,该方法在对象销毁之前执行。 |
@Profile | 表示当一个或多个指定的文件是活动的时,一个组件是有资格注册的。使用@Profile注解类或者方法,达到在不同情况下选择实例化不同的Bean。@Profile(“dev”)表示为dev时实例化。 |
@EnableAsync | 开启异步任务支持。注解在配置类上。 |
@Async | 注解在方法上标示这是一个异步方法,在类上标示这个类所有的方法都是异步方法。 |
@EnableScheduling | 注解在配置类上,开启对计划任务的支持。 |
@Scheduled | 注解在方法上,声明该方法是计划任务。支持多种类型的计划任务:cron,fixDelay,fixRate |
@Conditional | 根据满足某一特定条件创建特定的Bean |
@Enable* | 通过简单的@Enable来开启一项功能的支持。所有@Enable注解都有一个@Import注解,@Import是用来导入配置类的,这也就意味着这些自动开启的实现其实是导入了一些自动配置的Bean(1.直接导入配置类2.依据条件选择配置类3.动态注册配置类) |
@RunWith | 这个是Junit的注解,springboot集成了junit。一般在测试类里使用:@RunWith(SpringJUnit4ClassRunner.class) — SpringJUnit4ClassRunner在JUnit环境下提供Sprng TestContext Framework的功能 |
@ContextConfiguration | 用来加载配置ApplicationContext,其中classes属性用来加载配置类:@ContextConfiguration(classes = {TestConfig.class(自定义的一个配置类)}) |
@ActiveProfiles | 用来声明活动的profile–@ActiveProfiles(“prod”(这个prod定义在配置类中)) |
@EnableWebMvc | 用在配置类上,开启SpringMvc的Mvc的一些默认配置:如ViewResolver,MessageConverter等。同时在自己定制SpringMvc的相关配置时需要做到两点:1.配置类继承WebMvcConfigurerAdapter类2.就是必须使用这个@EnableWebMvc注解。 |
@RequestMapping | 用来映射web请求(访问路径和参数),处理类和方法的。可以注解在类和方法上,注解在方法上的@RequestMapping路径会继承注解在类上的路径。同时支持Serlvet的request和response作为参数,也支持对request和response的媒体类型进行配置。其中有value(路径),produces(定义返回的媒体类型和字符集),method(指定请求方式)等属性。 |
@ResponseBody | 将返回值放在response体内。返回的是数据而不是页面 |
@RequestBody | 允许request的参数在request体中,而不是在直接链接在地址的后面。此注解放置在参数前。 |
@PathVariable | 放置在参数前,用来接受路径参数。 |
@RestController | 组合注解,组合了@Controller和@ResponseBody,当我们只开发一个和页面交互数据的控制层的时候可以使用此注解。 |
@ControllerAdvice | 用在类上,声明一个控制器建言,它也组合了@Component注解,会自动注册为Spring的Bean。 |
@ExceptionHandler | 用在方法上定义全局处理,通过他的value属性可以过滤拦截的条件:@ExceptionHandler(value=Exception.class)–表示拦截所有的Exception。 |
@ModelAttribute | 将键值对添加到全局,所有注解了@RequestMapping的方法可获得次键值对(就是在请求到达之前,往model里addAttribute一对name-value而已)。 |
@InitBinder | 通过@InitBinder注解定制WebDataBinder(用在方法上,方法有一个WebDataBinder作为参数,用WebDataBinder在方法内定制数据绑定,例如可以忽略request传过来的参数Id等)。 |
@WebAppConfiguration | 一般用在测试上,注解在类上,用来声明加载的ApplicationContext是一个WebApplicationContext。他的属性指定的是Web资源的位置,默认为src/main/webapp,我们可以修改为:@WebAppConfiguration(“src/main/resources”)。 |
@EnableAutoConfiguration | 此注释自动载入应用程序所需的所有Bean——这依赖于Spring Boot在类路径中的查找。该注解组合了@Import注解,@Import注解导入了EnableAutoCofigurationImportSelector类,它使用SpringFactoriesLoader.loaderFactoryNames方法来扫描具有META-INF/spring.factories文件的jar包。而spring.factories里声明了有哪些自动配置。 |
@SpingBootApplication | SpringBoot的核心注解,主要目的是开启自动配置。它也是一个组合注解,主要组合了@Configurer,@EnableAutoConfiguration(核心)和@ComponentScan。可以通过@SpringBootApplication(exclude={想要关闭的自动配置的类名.class})来关闭特定的自动配置。 |
@ImportResource | 虽然Spring提倡零配置,但是还是提供了对xml文件的支持,这个注解就是用来加载xml配置的。例:@ImportResource({“classpath |
@ConfigurationProperties | 将properties属性与一个Bean及其属性相关联,从而实现类型安全的配置。例:@ConfigurationProperties(prefix=”authot”,locations={“classpath |
@ConditionalOnBean | 条件注解。当容器里有指定Bean的条件下。 |
@ConditionalOnClass | 条件注解。当类路径下有指定的类的条件下。 |
@ConditionalOnExpression | 条件注解。基于SpEL表达式作为判断条件。 |
@ConditionalOnJava | 条件注解。基于JVM版本作为判断条件。 |
@ConditionalOnJndi | 条件注解。在JNDI存在的条件下查找指定的位置。 |
@ConditionalOnMissingBean | 条件注解。当容器里没有指定Bean的情况下。 |
@ConditionalOnMissingClass | 条件注解。当类路径下没有指定的类的情况下。 |
@ConditionalOnNotWebApplication | 条件注解。当前项目不是web项目的条件下。 |
@ConditionalOnResource | 条件注解。类路径是否有指定的值。 |
@ConditionalOnSingleCandidate | 条件注解。当指定Bean在容器中只有一个,后者虽然有多个但是指定首选的Bean。 |
@ConditionalOnWebApplication | 条件注解。当前项目是web项目的情况下。 |
@EnableConfigurationProperties | 注解在类上,声明开启属性注入,使用@Autowired注入。例:@EnableConfigurationProperties(HttpEncodingProperties.class)。 |
@AutoConfigureAfter | 在指定的自动配置类之后再配置。例:@AutoConfigureAfter(WebMvcAutoConfiguration.class) |
- 参考:
- Spring中必须掌握的25个注解:https://juejin.cn/post/7001843959731339271 (opens new window)
# 常用注解
# 🥝声明bean的注解
# @Component
表示一个带注释的类是一个“组件”,成为Spring管理的Bean。当使用基于注解的配置和类路径扫描时,这些类被视为自动检测的候选对象。同时@Component还是一个元注解。
# @Service
组合注解(组合了@Component注解),应用在service层(业务逻辑层)。
# @Repository
组合注解(组合了@Component注解),应用在dao层(数据访问层)。
# @Controller
组合注解(组合了@Component注解),应用在MVC层(控制层),DispatcherServlet会自动扫描注解了此注解的类,然后将web请求映射到注解了@RequestMapping的方法上。
# 🥥注入bean的注解
# @Autowired
Spring提供的工具(由Spring的依赖注入工具(BeanPostProcessor、BeanFactoryPostProcessor)自动注入)。
# @Resource
由JSR-250提供。
# @Inject
由JSR-250提供。
# 🍇Java配置类相关注解
# @Configuration
声明当前类是一个配置类,内部组合了 @Component 注解,表明这个类是一个bean(相当于一个Spring配置的xml文件)(类上)。
# @Bean
注解在方法上,声明当前方法的返回值为一个Bean。返回的Bean对应的类中可以定义init()方法和destroy()方法,然后在@Bean(initMethod=”init”,destroyMethod=”destroy”)定义,在构造之后执行init,在销毁之前执行destroy。(方法上)
# @ComponentScan
自动扫描指定包下所有使用@Service、@Component、@Controller、@Repository的类并注册(类上)。
# @WishlyConfiguration
为@Configuration与@ComponentScan的组合注解,可以替代这两个注解。
# 🍈切面(AOP)相关注解
# @Aspect
声明一个切面(类上) 使用@After、@Before、@Around定义建言(advice),可直接将拦截规则(切点)作为参数。 @After :在方法执行之后执行(方法上)。 @Before: 在方法执行之前执行(方法上)。 @Around: 在方法执行之前与之后执行(方法上)。 @PointCut: 声明切点 在java配置类中使用@EnableAspectJAutoProxy注解开启Spring对AspectJ代理的支持(类上)。
# 🍉@Bean的属性支持
# @Scope
定义我们采用什么模式去创建Bean(方法上,得有@Bean) 其设置类型包括:
- **Singleton **(单例,一个Spring容器中只有一个bean实例,默认模式);
- Prototype(每次调用新建一个bean);
- **Request **(web项目中,给每个http request新建一个bean);
- Session(web项目中,给每个http session新建一个bean);
- GlobalSession(给每一个 global http session新建一个Bean实例)。
# @PostConstruct
标注在方法上,该方法在构造函数执行完成之后执行。
# @PreDestory
标注在方法上,该方法在对象销毁之前执行。
# 🍊@Value注解
@Value 为属性注入值,经常与Sping EL表达式语言一起使用,注入普通字符,系统属性,表达式运算结果,其他Bean的属性,文件内容,网址请求内容,配置文件属性值等。
支持如下方式的注入:
- 注入普通字符
@Value("Michael Jackson")
String name;
2
- 注入操作系统属性
@Value("#{systemProperties['os.name']}")
String osName;
2
- 注入表达式结果
@Value("#{ T(java.lang.Math).random() * 100 }")
String randomNumber;
2
- 注入其它bean属性
@Value("#{domeClass.name}")
String name;
2
- 注入文件资源
@Value("classpath:com/hgs/hello/test.txt")
String Resource file;
2
- 注入网站资源
@Value("http://www.cznovel.com")
Resource url;
2
- 注入配置文件
@Value("${book.name}")
String bookName;
2
注入配置使用方法: ① 编写配置文件(test.properties) book.name=《三体》 ② @PropertySource 加载配置文件(类上) @PropertySource("classpath:com/hgs/hello/test/test.propertie") ③ 还需配置一个PropertySourcesPlaceholderConfigurer的bean。
# 🍌环境切换
# @Profile
通过设定Environment的ActiveProfiles来设定当前context需要使用的配置环境。(类或方法上)
# @Conditional
Spring4中可以使用此注解定义条件话的bean,通过实现Condition接口,并重写matches方法,从而决定该bean是否被实例化。(方法上)
# 🍋异步相关
# @EnableAsync
配置类中,通过此注解开启对异步任务的支持,叙事性AsyncConfigurer接口。(类上)
# @Async
在实际执行的bean方法使用该注解来申明其是一个异步任务(方法上或类上所有的方法都将异步,需要@EnableAsync开启异步任务)
# 🍍定时任务相关
# @EnableScheduling
在配置类上使用,开启计划任务的支持。(类上)
# @Scheduled
来申明这是一个任务,包括cron,fixDelay,fixRate等类型。(方法上,需先开启计划任务的支持)
# 🥭@Enable*注解说明
这些注解主要用来开启对xxx的支持。 @EnableAspectJAutoProxy 开启对AspectJ自动代理的支持。
@EnableAsync: 开启异步方法的支持。 @EnableScheduling: 开启计划任务的支持。 @EnableWebMvc :开启Web MVC的配置支持。 @EnableConfigurationProperties :开启对@ConfigurationProperties注解配置Bean的支持。 @EnableJpaRepositories:开启对SpringData JPA Repository的支持。 @EnableTransactionManagement:开启注解式事务的支持。 @EnableTransactionManagement: 开启注解式事务的支持。 @EnableCaching: 开启注解式的缓存支持。
# 🍎测试相关
# @RunWith
运行器,Spring中通常用于对JUnit的支持
# @ContextConfiguration
用来加载配置ApplicationContext,其中classes属性用来加载配置类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfig.class})
public class KjtTest {
private static Logger logger = LoggerFactory.getLogger("KjtTest");
@Autowired
Service service;
@Test
public void test() {
}
}
2
3
4
5
6
7
8
9
10
11
12
13
# SpringMVC相关注解
参考文章:
# @Controller
此注解使用在class上声明此类是一个Spring controller,是@Component注解的一种具体形式。
# @RequestMapping
用于映射Web请求,包括访问路径和参数。(类或方法上)。此注解可以用在class和method上,用来映射web请求到某一个handler类或者handler方法上。当此注解用在Class上时,就创造了一个基础url,其所有的方法上的@RequestMapping都是在此url之上的。
可以使用其method属性来限制请求匹配的http method。
@RequestMapping("/testRequestMapping")
@Controller
public class TestRequestMapping {
private static final String SUCCESS = "success";
/**
* 请求url : .../testRequestMapping/base
*/
@RequestMapping("/base")
public String base() {
System.out.println("TestRequestMapping.base()");
return SUCCESS;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
/**
* method 映射请求方法
* 该方法可以映射POST类型的请求
*/
@RequestMapping(value = "/post",method = RequestMethod.POST)
public String requestMethod() {
System.out.println("TestRequestMapping.requestMethod()");
return SUCCESS;
}
2
3
4
5
6
7
8
9
此外,Spring4.3之后引入了一系列@RequestMapping的变种。如下:
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
2
3
4
5
分别对应了相应method的RequestMapping配置。
# @ResponseBody
支持将返回值放在response内,而不是一个页面,通常用户返回json数据。(返回值旁或方法上) 此注解用在请求handler方法上。和@RequestBody作用类似,用于将方法的返回对象直接输出到http响应中。
@ResponseBody // 返回Json
@RequestMapping("requestJson")
public String getEmployee(@RequestBody Employee employee) { // 请求参数json
System.out.println(employee);
return new Date() + "hello --> " + employee;
}
2
3
4
5
6
# @RequestBody
此注解用在请求handler方法的参数上,用于将http请求的Body映射绑定到此参数上。HttpMessageConverter负责将对象转换为http请求。 允许request的参数在request体中,而不是在直接连接在地址后面。(放在参数前)
# @RestController
此注解用于class上,声明此controller返回的不是一个视图而是一个领域对象。 该注解为一个组合注解,相当于@Controller和@ResponseBody的组合,注解在类上,意味着,该Controller的所有方法都默认加上了@ResponseBody。
// 类中所有方法返回的数据直接写给浏览器(对象转为json格式)
//Spring Boot中定义的新注解,是 @Controller + @ResponseBody的组合注解
@RestController
public class HelloWorld {
@RequestMapping("/hello")
public String hello() {
return "Hello SpringBoot!";
}
}
2
3
4
5
6
7
8
9
# @RequestHeader
此注解用在请求handler方法的参数上,用于将http请求头部的值绑定到参数上。
@RequestMapping("/testRequestHeader")
@Controller
public class TestRequestHeader {
private static final String SUCCESS = "success";
@RequestMapping("/getHeaders")
public String getHeaders(@RequestHeader(value = "Host") String host,
@RequestHeader("Cookie")String cookie) {
System.out.println("Host: " + host);
System.out.println("Cookie: " + cookie);
return SUCCESS;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
# @RequestParam
此注解用在请求handler方法的参数上,用于将http请求参数的值绑定到参数上。
@RequestMapping("/testRequestParam")
@Controller
public class TestRequestParam {
private static final String SUCCESS = "success";
@RequestMapping("/getParams")
public String getPrams(@RequestParam(value = "username") String username,
@RequestParam(value = "age", required = false, defaultValue = "0") Integer age) {
System.out.println("params: " + username + "--" + age);
return SUCCESS;
}
}
2
3
4
5
6
7
8
9
10
11
12
# @PathVariable
用于接收路径参数,即用于将请求URL中的模板变量映射到功能处理方法的参数上。比如**@RequestMapping(“/hello/{name}”)**申明的路径,将注解放在参数中前,即可获取该值,通常作为Restful的接口实现方法。 此注解使用在请求handler方法的参数上。@RequestMapping可以定义动态路径,如:
@RequestMapping("/users/{uid}")
可以使用@PathVariable将路径中的参数绑定到请求方法参数上。
@RequestMapping("/users/{uid}")
public String execute(@PathVariable("uid")String uid){
}
2
3
# @SessionAttribute
此注解用于方法的参数上,用于将session中的属性绑定到参数。
# @SessionAttributes
此注解用于type级别,用于将JavaBean对象存储到session中。一般和**@ModelAttribute**注解一起使用。如下:
@SessionAttributes(value = {"user1", "user2"}, types = {String.class})
@Controller
public class TestSessionAttributes {
private static final String SUCCESS = "success";
@RequestMapping("/sessionAttributes")
public String sessionAttributes(Map<String, Object> map) {
User user1 = new User(1, "小明", 25);
User user2 = new User(2, "James", 25);
String school = "清华大学";
// 存入数据模型中
map.put("user1", user1);
map.put("user2", user2);
map.put("school", school);
return SUCCESS;
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# @RequestPart
此注解用在请求handler方法的参数上,用于将文件之类的multipart绑定到参数上。
# @ResponseStatus
此注解用于方法和exception类上,声明此方法或者异常类返回的http状态码。可以在Controller上使用此注解,这样所有的@RequestMapping都会继承。
# @ExceptionHandler
用于全局处理控制器里的异常。此注解使用在方法级别,声明对Exception的处理逻辑。可以指定目标Exception。
@ControllerAdvice //springMVC 全局异常处理
public class MyExceptionHandler1 {
//浏览器和客户端返回的都是json数据没有自适应效果
@ResponseBody
@ExceptionHandler(UserNotExistException.class) // 处理异常的类型
public Map<String, Object> handleException(Exception e) {
Map<String, Object> map = new HashMap<>();
map.put("code", "user notExist");
map.put("message", e.getMessage());
return map;
}
}
2
3
4
5
6
7
8
9
10
11
12
# @InitBinder
此注解使用在方法上,声明对 WebDataBinder 的初始化(绑定请求参数到JavaBean上的DataBinder)。 在controller上使用此注解可以自定义请求参数的绑定。
@Controller
public class InitBinderController {
// 设置不绑定对象中的gender属性(适用于需要手动处理该属性)
// 注意只作用当前controller
@InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.setDisallowedFields("gender");
}
@RequestMapping("/testInitBinder")
public String testInitBinder(Employee employee) {
System.out.println(employee);
return "success";
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# @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
}
2
3
4
5
6
7
需要注意的是默认Spring MVC是不支持矩阵变量的,需要开启。
<mvc:annotation-driven enable-matrix-variables="true"/>
注解配置则需要如下开启:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
2
3
4
5
6
7
8
9
# @ModelAttribute
本来的作用是绑定键值对到 Model 里,在 @ControllerAdvice 中是让全局的@RequestMapping都能获得在此处设置的键值对。
# @CookieValue
此注解用在@RequestMapping声明的方法的参数上,可以把HTTP cookie中相应名称的cookie绑定上去。
@RequestMapping("/testCookieValue")
@Controller
public class TestCookieValue {
private static final String SUCCESS = "success";
@RequestMapping("/getCookie")
public String getCookie(@CookieValue("JSESSIONID") String JSESSIONID) {
System.out.println("JSESSIONID = " + JSESSIONID);
return SUCCESS;
}
}
2
3
4
5
6
7
8
9
10
11
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() {
// ...
}
}
2
3
4
5
6
7
8
9
10
# @ControllerAdvice
此注解用于class上。前面说过可以对每一个controller声明一个ExceptionMethod。 这里可以使用@ControllerAdvice来声明一个类来统一对所有@RequestMapping方法来做@ExceptionHandler、@InitBinder以及@ModelAttribute处理。
# @RestControllerAdvice
此注解用于class上,同时引入了@ControllerAdvice和@ResponseBody两个注解。 (opens new window)
# SpringBoot相关注解
参考:
- 核心27注解:
- 注解详解: