zoukankan      html  css  js  c++  java
  • 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();
        }
    }

    运行结果:

  • 相关阅读:
    C语言和指针-回顾02-const
    Linux内核学习-使用exec创建socket
    Archlinux安装和配置
    apt-get install failed
    Insmod module : operation not permitted
    5.2.5.用开发板来调试模块
    5.2.4.最简单的模块源码分析3
    5.2.3.最简单的模块源码分析2
    5.2.1.开启驱动开发之路
    总线,设备,驱动的关系
  • 原文地址:https://www.cnblogs.com/dyppp/p/7741752.html
Copyright © 2011-2022 走看看