2.10@Repository、@Service和@Controller
戴着假发的程序员出品 抖音ID:戴着假发的程序员 欢迎关注
[查看视频教程]
这三个注解是我们在开发中经常用到的注解,我们来看看这些注解的源码。
1 package org.springframework.stereotype; 2 3 @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) 4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) 5 @java.lang.annotation.Documented 6 @org.springframework.stereotype.Component 7 public @interface Repository { 8 @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class) 9 java.lang.String value() default ""; 10 }
1 package org.springframework.stereotype; 2 3 @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) 4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) 5 @java.lang.annotation.Documented 6 @org.springframework.stereotype.Component 7 public @interface Service { 8 @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class) 9 java.lang.String value() default ""; 10 }
1 package org.springframework.stereotype; 2 3 @java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE}) 4 @java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME) 5 @java.lang.annotation.Documented 6 @org.springframework.stereotype.Component 7 public @interface Controller { 8 @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class) 9 java.lang.String value() default ""; 10 }
通过查看源码,我发现这三个注解都“继承”自@org.springframework.stereotype.Component。而且各自都没有特殊的扩展和属性。 所以这三个注解的功能和@Component完全相同。 既然完全相同为什么要出现这三个注解呢?
主要是为了提高我们代码的可读性。 我们都知道在实际开发中我们都是通过包扫描和注解的方式完成bean注册。
那么为了方便我们标记各种bean的不同种类就有了这三个注解。
@Repository : 一般都是用来标记数据持久化的类。
@Service:一般都是用来标记业务处理的类。
@Controller:一般都是用来标记后端控制器的类(参照web模块)。
当然其实这四个注解是可以互换的。
我是戴着假发的程序员,分享技术,分享经验,如果要转载,请注明:出自戴着假发的程序员

浙公网安备 33010602011771号