背景
想把一个类注册成为spring的bean并且加载入容器,经常会用到四个注解Service+Component+Controller+Repository,那么这四个注解有什么区别呢?本博客将查看源码进行阐述。
四大注解
基本注解Component
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default ""; // value可以给bean起名字
}
只要添加注解,就会被spring的容器识别,并且加载到容器中(在不被其他的过滤条件过滤的情况下)。
此注解为基本注解,Service、Controller、Repository全部都使用了这个注解,所以都具备被加载为bean的能力。
业务标识注解Service
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
@AliasFor(annotation = Component.class)
String value() default "";
}
可以看到,这里直接使用了Component注解,并且把value参数直接转交给了Component(类似于类的继承关系)
Controller、Repository注解
同上
个人评论
- 如果想注册成为bean,单一个Component就够了
- Service等注解,来自于不同的标准,在引入其他模块的时候(例如mybatis),可能会被第三方模块的反射读取,所以,当你知道bean用途的情况下,最好使用对应的类型