写点什么

Spring 常用注解

用户头像
ES_her0
关注
发布于: 2021 年 02 月 22 日

前言

Spring Boot 增加大量的注解进一步增强了开发效率。为什么要写这篇分析呢?因为往往随着开发经验的增长,有些注解虽然信手拈来却不知所以然,可能随便蒙一个能用跑通,但遇到某些问题时都要一遍遍的 Google。且不说深入设计理念和源码,至少要知道哪些注解用在哪些场合可以解决哪些问题。

今天浅尝辄止,介绍一下 spring bean 声明的几个注解。以下几个注解都可以用于 Bean 的声明,从习惯上说@Repository用于标记数据访问层,也就是 DAO 层;@Service用于标记 Service 层;@Controller用于标记 API 层;@Configuration@Bean则用于直接声明一个自定义的 bean;@Component则用于声明一个通用的组件。其实这么说,已经足够日常实用了,但这次再深入一点,探寻一些细节。

首先看一下 spring 官方的说明:

The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.

Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects.

For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

这段话可以概括为以下几点:

@Component

component 是一个标记超集,spring 管理的对象都是一个 component。其实以下几个注解的源码是这样的:

@Componentpublic @interface Service {    ….}
@Componentpublic @interface Repository { ….}
@Componentpublic @interface Controller {}
复制代码

那可能会产生疑问,我所有的组件都标记成@Component不就行了吗,简单省事。其实也可以,但就不能享受 spring 框架的一些别的福利了。

@Repository

此注解用于标记 DAO 层,并交给 spring 统一管理。spring 在收集到这个注解后,会把所有数据层的异常转换成 spring 的非受检异常。这样你的业务代码层面可以少写很多可能的受检异常。

@Service

用于标记业务处理的 Service,现阶段没有任何意义。但 spring 也说了,可能在未来增加一些特性来收特殊处理。

@Controller

用于标记 API,会有一个调度器来专门寻找项目中所有的@Controller类。而且@RequestMapping标记仅可用于标记了@Controller的类,在别的声明中不生效。

@Configuration @Bean

这两个注解源自与旧版本的 spring 的 xml 式的 bean 声明,一般用于自定义的 bean。

@Configurationclass VehicleFactoryConfig {
@Bean public Engine engine() { return new Engine(); }
}
复制代码

这样的 bean 可以在别的地方注入实用。

总结

以上总结了 spring 的常用 bean 声明注解的实用场景,下次应该不用 google 也不会用错或者迷惑了。

用户头像

ES_her0

关注

还未添加个人签名 2018.03.21 加入

还未添加个人简介

评论

发布
暂无评论
Spring常用注解