zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

Spring Boot驱动模块

2023-04-18 15:54:54 时间

在spring框架中,我们可以看到有许多的@Enablexxx注解,如spring的Cachine模块@EnableCaching,在springboot中有自动装配模块@EnableAutoConfiguration、OAuth2单点登录@EnableOAuth2Sso,在springcloud中还有Eureka服务器模块@EnableEurekaServer、Feign客户端模块@EnableFeignClients等@Enable注解。@Enablexx注解能够简化装配步骤,实现按需装配,同时屏蔽组件装配细节,不过要使用@Enable模块也必须手动触发,加注解在某个配置的bean上。

  • 手写@Enable模块分两类实现,一种是“注解驱动”,另一种是“接口编程”,后者更难,也可以再细分为两种实现方式。在手写@Enable模块的时候,也可以看看spring框架已定义好的@Enable相关注解,这样可以有助于我们理解该模块的设计思想。
  • 实现@Enable模块的核心注解是@Import注解,其职责在于装载导入类(Importing Class),将其定义为Srping Bean,导入类主要为@Configuration Class、ImportSelector实现类以及ImportBeanDefinitionRegistrar实现类三种,但@Import注解的功能不仅仅是为了实现@Enable模块,这点需要注意到,在了解springboot starter自动装配过程中就可以看到很多@Import注解的身影。
  • @Import注解源码,看value方法注释可值,所“@Import”的value值有三种类类型,@Configuration注解修饰类、实现ImportSelector接口类、实现ImportBeanDefinitionRegistrar接口类,“ or regular component classes to import” 或者有规则的被@component注解修饰的类,因为@Configuration也是由@component注解修饰,故也合理。
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Import {
    /**
     * {@link Configuration @Configuration}, {@link ImportSelector},
     * {@link ImportBeanDefinitionRegistrar}, or regular component classes to import.
     */
    Class<?>[] value();
}
  • 本文代码项目目录结构如图所示,在spring-boot项目的spring-boot-enable模块:

spring-boot-enable代码目录结构.png

  • springboot项目 默认扫描引导类 目录下有@Componet注解的类或@Componet注解的派生注解,如@Configuration、@Service等注解,而@Import注解的功能是装载导入类,为了演示@Import注解的功能实现@Enable模块,示例代码没写在引导类SpringBootEnableApplication的com.dayue.springbootenable包目录下, 避免被springboot扫描并自动装载,故写在了com.dayue.enable.xxxx包目录下
(1)方式一:“注解驱动”,@Import导入xxxConfiguration类
  • domain Student类
@Data
public class Student {
    private String name;
    private Integer age;
}
  • domain Teacher类
@Data
public class Teacher {
    private String name;
    private Integer age;
}
  • HelloWorldConfiguration类
@Configuration
@Slf4j
public class HelloWorldConfiguration {
    @Bean
    public Student student() {
        log.info("初始化student");
        return new Student();
    }
}
  • @EnableHelloWorld注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(HelloWorldConfiguration.class)
public @interface EnableHelloWorld {
}

启动项目,我们会发现Student

bean并没有被springboot扫描并装载,然后在引导类SpringBootEnableApplication上面加注解@EnableHelloWorld,再次启动项目,通过日志可以看到Student

bean已经被初始化了。

@SpringBootApplication
@EnableHelloWorld
public class SpringBootEnableApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootEnableApplication.class, args);
    }
}

方式一注解驱动,启动项目.png

(2)方式二:接口编程,@Import导入实现ImportSelector类

使用接口编程方式实现@Enable模块,需要实现ImportSelector类或ImportBeanDefinitionRegistrar类,相对于方式一,导入xxxConfiguration类,实现ImportSelector类和实现ImportBeanDefinitionRegistrar类的方式弹性更大,可以动态地选择一个或者多个@Componet类进行导入,使用的是Spring注解元信息AnnotationMetadata作为方法参数。

示例代码通过一个接口,两个接口实现类,在@Enable模块中通过传入枚举值实现动态选择其中一个实现类注册为Spring

Bean供controller层来使用。

  • ActionType枚举类
public enum ActionType {
    /**
     * 老师
     */
    TEACHER,
    /**
     * 学生
     */
    STUDENT
}
  • @EnableActionServer注解,后面实现ImportSelector类通过枚举值来动态选择实现类,老师上课或者学生上课
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ServerImportSelector.class)
public @interface EnableActionServer {
    /**
     * 设置动作类型,默认为老师上课
     */
    ActionType serverType() default ActionType.TEACHER;
}
  • ActionServer接口类
public interface ActionServer {
    /**
     * 动作
     */
    String action();
}
  • StudentActionServerImpl实现类
@Slf4j
@Service
public class StudentActionServerImpl implements ActionServer {
    @Bean
    public Student studentone() {
        log.info("初始化student bean");
        return new Student();
    }
    @Override
    public String action() {
        log.info("学生上课");
        return "学生上课";
    }
}
  • TeacherActionServerImpl实现类
@Slf4j
@Service
public class TeacherActionServerImpl implements ActionServer {
    @Bean
    public Teacher teacherone() {
        log.info("初始化teacher bean");
        return new Teacher();
    }
    @Override
    public String action() {
        log.info("老师上课");
        return "老师上课";
    }
}
  • ServerImportSelector实现类,实现ImportSelector的selectImports方法,方法参数是Spring注解元信息AnnotationMetadata,通过该参数可以获取注解@EnableActionServer相关元信息,如@EnableActionServer注解的属性方法serverType(),返回其定义好的值,代码通过判断定义的ActionType来选择返回不同的类名。
@Slf4j
public class ServerImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        //获取注解@EnableActionServer元信息
        Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(EnableActionServer.class.getName());
        assert annotationAttributes != null;
        //通过获取的注解@EnableActionServer元信息,取定义好的方法属性,并把对象Object强制转换为ActionType枚举类型
        ActionType serverType = (ActionType) annotationAttributes.get("serverType");
        log.info("serverType:{},getServerType(serverType):{}", serverType, getServerType(serverType));
        //最后返回要选择的类名,注册为spring bean组件
        return new String[]{getServerType(serverType)};
    }
    //封装一层,通过枚举值返回不同的类名
    public String getServerType(ActionType serverType) {
        Map<ActionType, String> serverClassMap; serverClassMap = new HashMap<>(2);
        serverClassMap.put(ActionType.TEACHER, TeacherActionServerImpl.class.getName());
        serverClassMap.put(ActionType.STUDENT, StudentActionServerImpl.class.getName());
        return serverClassMap.get(serverType);
    }
}

在controller层注入ActionServer,然后启动项目,可以发现报错了。报错是因为没有定义好Spring

Bean,题外话:当然可以通过@Bean的方式去注入某个实现类或者在实现类上加@ Server注解再选择其中之一的实现类去注入。

  • ActionServerController类
@RestController
@RequestMapping("/api/actionServer")
public class ActionServerController {
    @Autowired
    private ActionServer actionServer;
    @GetMapping("/actionType")
    public String actionType() {
        return actionServer.action();
    }
}

注入ActionServer类报错.png

最后,我们也用实现ImportSelector接口类的方式去实现@Enable模块,那么在引导类上加上注解@EnableActionServer(serverType

= ActionType.STUDENT)即可,再次启动项目

@SpringBootApplication
@EnableActionServer(serverType = ActionType.STUDENT)
public class SpringBootEnableApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootEnableApplication.class, args);
    }
}

方式二启动项目.png

浏览器访问接口.png

(3)方式三:接口编程,@Import导入实现ImportBeanDefinitionRegistrar类

ImportBeanDefinitionRegistrar相对于ImportSelector而言,编程复杂度更高,除了注解元信息AnnotationMetadata作为入参外,接口将定义Bean的注册交给开发人员。示例代码复用方式二的选择实现类逻辑,故直接通过new

ServerImportSelector()的方式来复用实现好的selectImports方法,入参即为注解元信息AnnotationMetadata,返回类名,最后完成注册返回类名的类为Spring

Bean。

  • ServerImportBeanDefinitionRegistrar实现ImportBeanDefinitionRegistrar类
public class ServerImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //复用前面实现好的ImportSelector
        ImportSelector importSelector = new ServerImportSelector();
        //筛选ClassNames集合
        String[] selectClassNames = importSelector.selectImports(importingClassMetadata);
        Stream.of(selectClassNames)
                //转化为 BeanDefinitionBuilder 对象
                .map(BeanDefinitionBuilder::genericBeanDefinition)
                //转化为 BeanDefinition 对象
                .map(BeanDefinitionBuilder::getBeanDefinition)
                //注册 BeanDefinition 到 BeanDefinitionRegistry
                .forEach(beanDefinition -> BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry));
    }
}

接着修改前面写好的注解@EnableActionServer注解的@Import导入类,修改为@Import(ServerImportBeanDefinitionRegistrar.class)

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
//@Import(ServerImportSelector.class)
@Import(ServerImportBeanDefinitionRegistrar.class)
public @interface EnableActionServer {
    /**
     * 设置动作类型,默认为老师上课
     */
    ActionType serverType() default ActionType.TEACHER;
}