Spring Boot實戰筆記(九)-- Spring進階話題(組合註解與元註解)

來源:互聯網
上載者:User

標籤: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進階話題(組合註解與元註解)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.