Spring注解 @Component、@Controller、@Service、@Repository

来源:互联网 发布:linux kernel init 编辑:程序博客网 时间:2024/06/05 18:42


1.@Component

在annotaion配置注解中用@Component来表示一个通用注释,用于说明一个类是一个spring容器管理的类。也就是该类已经进入到spring的管理容器中了。而@Controller, @Service, @Repository是@Component注解的细化,也可以说是具体化,这三个注解比@Component带有更多的语义,它们分别对应了控制层、服务层、持久层的类。

@Component注解源码如下:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Component {/** * 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 "";}

2.@Controller

@Controller注解表明这个类是一个控制器类,用于标注控制层组件,也就是Action。


@Controller注解源码如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Controller {/** * 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 "";}

3.@Service

@Service注解表明这个类是一个业务类,用于标注业务层组件。


@Service注解源码如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @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 "";}

4.@Repository

@Repository注解表明这个类是一个持久化类,用于标注持久化层组件。


@Repository注解源码如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface Repository {/** * 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 "";}

总结:
@Component、@Controller、@Service、@Repository注解的元注解都相同,包括如下三个:
@Target元注解:表示标注的注解用于什么地方,可选的值包括:
          ElemenetType.CONSTRUCTOR 构造器声明 
          ElemenetType.FIELD 域声明(包括 enum 实例) 
          ElemenetType.LOCAL_VARIABLE 局部变量声明
          ElemenetType.ANNOTATION_TYPE 作用于注解量声明
          ElemenetType.METHOD 方法声明
          ElemenetType.PACKAGE 包声明 
          ElemenetType.PARAMETER 参数声明 
          ElemenetType.TYPE 类,接口(包括注解类型)或enum声明
根据上述的源码中可以看到@Target的值为ElemenetType.TYPE。

@Retention元注解:表示在什么级别保存该注解信息。可选的值包括:
          RetentionPolicy.SOURCE 注解将被编译器丢弃 
          RetentionPolicy.CLASS 注解在class文件中可用,但会被VM丢弃 
          RetentionPolicy.RUNTIME VM将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
根据上述的源码中可以看到@Retention的值为RetentionPolicy.RUNTIME

@Documented元注解:表示将此注解包含在javadoc中,此注解会被javadoc工具提取成文档。

@Controller、@Service和@Repository注解又被@Component注解标注,说明这三个注解是@Component注解的具体化注解。

补充:1.关于元注解的内容会在后续文章中进行介绍。
           2.关于Spring容器的注解扫描过程和原理会在后续文章中进行介绍。



0 0
原创粉丝点击