几个注解本质上没有什么区别,至少在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