SpringBoot-模式注解
SpringBoot-模式注解
学习核心
- 模式注解概念核心和场景应用
学习资料
模式注解概念核心
Spring 框架中有很多可用的注解,其中有一类注解称模式注解(Stereotype Annotations),包括 @Component、@Service、@Controller、@Repository 等。只要在相应的类上标注这些注解,并配置开启自动扫描(如在 XML 中配置 <context:component-scan base-package="xxx.xxx.xx"/> 或使用注解 @ComponentScan),就能成为 Spring 中组件(Bean)
从最终的效果上来看,@Component, @Service,@Controller,@Repository 起到的作用完全一样,那为何还需要多个不同的注解?
从官方 wiki 可以看到原因。
A stereotype annotation is an annotation that is used to declare the role that a component plays within the application. For example, the
@Repositoryannotation in the Spring Framework is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO).
不同的模式注解虽然功能相同,但是代表含义却不同:
- 标注
@Controller注解,这类组件就可以表示为 WEB 控制层 ,处理各种 HTTP 交互 - 标注
@Service可以表示为内部服务层 ,处理内部服务各种逻辑 - 标注
@Repository可以代表示为数据控制层,代表数据库增删改查动作
通过不同模式注解带来了不同的含义,清晰将服务进行分层。除了上面的作用,特定的模式注解,Spring 可能会在未来增加额外的功能语义。如现在 @Repository 注解,可以增加异常的自动转换功能。
因此对于分层服务开发时最好使用各自特定语义的模式注解来更加清晰地进行服务分层
模式注解原理分析
在 Spring 中任何标注 @Component 的组件都可以成为扫描的候选对象。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
另外任何使用 @Component 标注的注解,如 @Service,当其标注组件时,也能被当做扫描的候选对象,可跟踪@Service实现
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
可以参考@Service注解的定义,实现自定义注解,让自定义注解也拥有类似的功能(添加@Component标注)
