Spring Boot實戰筆記(九)-- Spring高級話題(組合注解與元注解)


一、組合注解與元注解

  從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;

@Service
public class DemoService {

    public void outputResult(){
        System.out.println("從組合注解配置也可獲得Bean");
    }
}

  (3)新的配置類

package com.ecworking.annotation;

@WiselyConfiguration(value = "com.ecworking.annotation") //使用@WiselyConfiguration 代替@Configuration和@ComponentScan
public 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();
    }
}

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM