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

    运行结果:

  • 相关阅读:
    [转载]instanceof和typeof区别
    【转载】DNN架构
    Delphi实现高性能的Socket通讯服务器(完成端口模型IOCP)
    record, packed record和变体记录
    Delphi操作Word的几个知识点
    WinSock学习笔记6:IOCP完成端口模型
    MyEclipse 常用设置和操作方法
    PAIP.一些流氓软件的流氓营销方法.txt
    qq安全使用指南.txt
    海量数据高性能分页
  • 原文地址:https://www.cnblogs.com/dyppp/p/7741752.html
Copyright © 2011-2022 走看看