Spring Boot实战笔记(九)-- Spring高级话题(组合注解与元注解)

2023-06-20,,

一、组合注解与元注解

  从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();
}
}

运行结果:

Spring Boot实战笔记(九)-- Spring高级话题(组合注解与元注解)的相关教程结束。

《Spring Boot实战笔记(九)-- Spring高级话题(组合注解与元注解).doc》

下载本文的Word格式文档,以方便收藏与打印。