【最详细】注解@controller@service@component@repository区别

人生之路不会是一帆风顺的,我们会遇上顺境,也会遇上逆境,在所有成功路上折磨你的,背后都隐藏着激励你奋发向上的动机,人生没有如果,只有后果与结果,成熟,就是用微笑来面对一切小事。

导读:本篇文章讲解 【最详细】注解@controller@service@component@repository区别,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

几个注解本质上没有什么区别,至少在spring2.5版本里,这几个注解本质是一样的(当然,新的版本有什么变化目前还没细查),命名不一样主要是为了区分类的作用和所属层级:
@Repository:持久层,用于标注数据访问组件,即DAO组件。
@Service:业务层,用于标注业务逻辑层主键。
@Controller:控制层,用于标注控制层组件。
@Component:当你不确定是属于哪一层的时候使用。
之所以区分开几种类型,一是spring想在以后的版本中为它们添加特殊技能,二是这种分层的做法使web架构更清晰,易读性与维护性更好。
 

/**
 * Indicates that an annotated class is a "Service", originally defined by Domain-Driven
 * Design (Evans, 2003) as "an operation offered as an interface that stands alone in the
 * model, with no encapsulated state."
 *
 * <p>May also indicate that a class is a "Business Service Facade" (in the Core J2EE
 * patterns sense), or something similar. This annotation is a general-purpose stereotype
 * and individual teams may narrow their semantics and use as appropriate.
 *
 * <p>This annotation serves as a specialization of {@link Component @Component},
 * allowing for implementation classes to be autodetected through classpath scanning.
 *
 * @author 
 * @since 2.5
 * @see Component
 * @see Repository
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     * @return the suggested component name, if any
     */
    String value() default "";

}

从@service的源码看,service仍然是使用了@Component注解(@Controller与@Repository与service一样,这里就不贴源码了)。
component即组件,相当于xml配置文件中的bean申明,通过spring的自动扫描机制,在规定的类路径中寻找标注了@Component,@Service,@Repository,@Controller注解的类,并把这些类纳入进容器中进行管理。getBean的默认名称是类名(头字母小写),并且是单例的,如果想自定义,可以使用@Service(“beanName”)@Scope(“prototype”)来改变。
 

/**自动扫描base-package目录下的所有文件,包括子目录**/
<context:component-scan base-package="com.user.*"/>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/124477.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!