Spring常用注解 | 8月更文挑战

177 阅读3分钟

前言

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。其实以下几个注解的源码是这样的:

@Component
public @interface Service {
    ….
}
​
@Component
public @interface Repository {
    ….
}
​
@Component
public @interface Controller {
    …
}

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

@Repository

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

@Service

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

@Controller

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

@Configuration @Bean

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

@Configuration
class VehicleFactoryConfig {
​
    @Bean
    public Engine engine() {
        return new Engine();
    }
​
}

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

总结

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