您好,登錄后才能下訂單哦!
本文實例講述了Spring的組合注解和元注解原理與用法。分享給大家供大家參考,具體如下:
一 點(diǎn)睛
從Spring 2開始,為了相應(yīng)JDK 1.5推出的注解功能,Spring開始加入注解來替代xml配置。Spring的注解主要用來配置和注入Bean,以及AOP相關(guān)配置。隨著注解的大量使用,尤其相同的多個注解用到各個類或方法中,會相當(dāng)繁瑣。出現(xiàn)了所謂的樣本代碼,這是Spring設(shè)計要消除的代碼。
元注解:可以注解到別的注解上去的注解。
組合注解:被注解的注解,組合注解具備其上的元注解的功能。
Spring的很多注解都可以作為元注解,而且Spring本身已經(jīng)有很多組合注解,如@Configuration就是一個組合了@Component的注解,表明被注解的類其實也是一個Bean。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { String value() default ""; }
二 實戰(zhàn)項目
自定義一個組合注解,它的元注解是@Configuration和@ConfigurationScan
三 實戰(zhàn)
1 自定義組合注解
package com.wisely.highlight_spring4.ch4.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration //組合@Configuration元注解 @ComponentScan //組合@ComponentScan元注解 public @interface WiselyConfiguration { String[] value() default {}; //覆蓋value參數(shù) }
2 編寫服務(wù)類
package com.wisely.highlight_spring4.ch4.annotation; import org.springframework.stereotype.Service; @Service public class DemoService { public void outputResult(){ System.out.println("從組合注解配置照樣獲得的bean"); } }
3 編寫配置類
package com.wisely.highlight_spring4.ch4.annotation; @WiselyConfiguration("com.wisely.highlight_spring4.ch4.annotation") public class DemoConfig { }
4 編寫主類
package com.wisely.highlight_spring4.ch4.annotation; import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Main { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoConfig.class); DemoService demoService = context.getBean(DemoService.class); demoService.outputResult(); context.close(); } }
四 運(yùn)行
從組合注解配置照樣獲得的bean
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Spring框架入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設(shè)計有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。