spring应用手册-IOC(注解实现)-(10)-@Repository、@Service和@Controller

戴着假发的程序员出品

@Repository、@Service和@Controller

spring应用手册(第二部分)


这三个注解是我们在开发中经常用到的注解,我们来看看这些注解的源码。

package org.springframework.stereotype;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.stereotype.Component
public @interface Repository {
    @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class)
    java.lang.String value() default "";
}
package org.springframework.stereotype;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.stereotype.Component
public @interface Service {
    @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class)
    java.lang.String value() default "";
}
package org.springframework.stereotype;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
@org.springframework.stereotype.Component
public @interface Controller {
    @org.springframework.core.annotation.AliasFor(annotation = org.springframework.stereotype.Component.class)
    java.lang.String value() default "";
}

通过查看源码,我发现这三个注解都“继承”自@org.springframework.stereotype.Component。而且各自都没有特殊的扩展和属性。 所以这三个注解的功能和@Component完全相同。 既然完全相同为什么要出现这三个注解呢?

主要是为了提高我们代码的可读性。 我们都知道在实际开发中我们都是通过包扫描和注解的方式完成bean注册。

那么为了方便我们标记各种bean的不同种类就有了这三个注解。

@Repository : 一般都是用来标记数据持久化的类。

@Service:一般都是用来标记业务处理的类。

@Controller:一般都是用来标记后端控制器的类(参照web模块)。

当然其实这四个注解是可以互换的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴着假发的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值