Spring的组合注解和元注解原理与用法详解
本文实例讲述了Spring的组合注解和元注解原理与用法。分享给大家供大家参考,具体如下:
一点睛
从Spring2开始,为了相应JDK1.5推出的注解功能,Spring开始加入注解来替代xml配置。Spring的注解主要用来配置和注入Bean,以及AOP相关配置。随着注解的大量使用,尤其相同的多个注解用到各个类或方法中,会相当繁琐。出现了所谓的样本代码,这是Spring设计要消除的代码。
元注解:可以注解到别的注解上去的注解。
组合注解:被注解的注解,组合注解具备其上的元注解的功能。
Spring的很多注解都可以作为元注解,而且Spring本身已经有很多组合注解,如@Configuration就是一个组合了@Component的注解,表明被注解的类其实也是一个Bean。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public@interfaceConfiguration{ Stringvalue()default""; }
二实战项目
自定义一个组合注解,它的元注解是@Configuration和@ConfigurationScan
三实战
1自定义组合注解
packagecom.wisely.highlight_spring4.ch3.annotation; importjava.lang.annotation.Documented; importjava.lang.annotation.ElementType; importjava.lang.annotation.Retention; importjava.lang.annotation.RetentionPolicy; importjava.lang.annotation.Target; importorg.springframework.context.annotation.ComponentScan; importorg.springframework.context.annotation.Configuration; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration//组合@Configuration元注解 @ComponentScan//组合@ComponentScan元注解 public@interfaceWiselyConfiguration{ String[]value()default{};//覆盖value参数 }
2编写服务类
packagecom.wisely.highlight_spring4.ch3.annotation; importorg.springframework.stereotype.Service; @Service publicclassDemoService{ publicvoidoutputResult(){ System.out.println("从组合注解配置照样获得的bean"); } }
3编写配置类
packagecom.wisely.highlight_spring4.ch3.annotation; @WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation") publicclassDemoConfig{ }
4编写主类
packagecom.wisely.highlight_spring4.ch3.annotation; importorg.springframework.context.annotation.AnnotationConfigApplicationContext; publicclassMain{ publicstaticvoidmain(String[]args){ AnnotationConfigApplicationContextcontext= newAnnotationConfigApplicationContext(DemoConfig.class); DemoServicedemoService=context.getBean(DemoService.class); demoService.outputResult(); context.close(); } }
四运行
从组合注解配置照样获得的bean
更多关于java相关内容感兴趣的读者可查看本站专题:《Spring框架入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。