標籤:element ace lan ges 相關 xml配置 rgs port put
一、組合註解與元註解
從Spring 2開始,為了響應JDK 1.5推出的註解功能,Spring開始大量加入註解來替代xml配置。Spring的註解主要用來配置注入Bean,切面相關配置(@Transactional)。隨著註解的大量使用,尤其相同的多個註解用到各個類中,會相當囉嗦。這就是所謂的模板代碼,是Spring設計原則中要消除的代碼。
所謂元註解其實就是可以註解到別的註解上的註解,被註解的註解稱之為組合註解,組合註解具備元註解的功能。Spring的很多註解都可以作為元註解,而且Spring本身已經有很多組合註解,如@Configuration就是一個組合@Component註解,表明這個類其實也是一個Bean。
在之前的學習中大量使用@Configuration和@ComponentScan註解到配置類上,下面將這兩個元註解組成一個組合註解,這樣我們只需寫一個註解就可以表示兩個註解。
樣本:
(1)樣本組合註解
package com.ecworking.annotation;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import java.lang.annotation.*;@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Configuration //組合@Configuration元註解@ComponentScan //組合@ComponentScan元註解public @interface WiselyConfiguration { String[] value() default {}; // 覆蓋value參數}
(2)示範服務Bean。
package com.ecworking.annotation;import org.springframework.stereotype.Service;@Servicepublic class DemoService { public void outputResult(){ System.out.println("從組合註解配置也可獲得Bean"); }}
(3)新的配置類
package com.ecworking.annotation;@WiselyConfiguration(value = "com.ecworking.annotation") //使用@WiselyConfiguration 代替@Configuration和@ComponentScanpublic class DemoConfig {}
(4)運行
package com.ecworking.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(); }}
運行結果:
Spring Boot實戰筆記(九)-- Spring進階話題(組合註解與元註解)