Spring的組合註解和元註解原理與用法詳解
阿新 • • 發佈:2020-01-07
本文例項講述了Spring的組合註解和元註解原理與用法。分享給大家供大家參考,具體如下:
一 點睛
從Spring 2開始,為了相應JDK 1.5推出的註解功能,Spring開始加入註解來替代xml配置。Spring的註解主要用來配置和注入Bean,以及AOP相關配置。隨著註解的大量使用,尤其相同的多個註解用到各個類或方法中,會相當繁瑣。出現了所謂的樣本程式碼,這是Spring設計要消除的程式碼。
元註解:可以註解到別的註解上去的註解。
組合註解:被註解的註解,組合註解具備其上的元註解的功能。
Spring的很多註解都可以作為元註解,而且Spring本身已經有很多組合註解,如@Configuration就是一個組合了@Component的註解,表明被註解的類其實也是一個Bean。
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { String value() default ""; }
二 實戰專案
自定義一個組合註解,它的元註解是@Configuration和@ConfigurationScan
三 實戰
1 自定義組合註解
package com.wisely.highlight_spring4.ch3.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引數 }
2 編寫服務類
package com.wisely.highlight_spring4.ch3.annotation; import org.springframework.stereotype.Service; @Service public class DemoService { public void outputResult(){ System.out.println("從組合註解配置照樣獲得的bean"); } }
3 編寫配置類
package com.wisely.highlight_spring4.ch3.annotation; @WiselyConfiguration("com.wisely.highlight_spring4.ch3.annotation") public class DemoConfig { }
4 編寫主類
package com.wisely.highlight_spring4.ch3.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(); } }
四 執行
從組合註解配置照樣獲得的bean
更多關於java相關內容感興趣的讀者可檢視本站專題:《Spring框架入門與進階教程》、《Java資料結構與演算法教程》、《Java操作DOM節點技巧總結》、《Java檔案與目錄操作技巧彙總》和《Java快取操作技巧彙總》
希望本文所述對大家java程式設計有所幫助。