Springboot 的动态装载-Registrar

  1. 自定义 registrar,实现 ImportBeanDefinitionRegistrar 接口

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    public class MyRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
    BeanDefinitionRegistry registry) {
    BeanDefinition beanDefinition=new GenericBeanDefinition();
    beanDefinition.setBeanClassName(MyService.class.getName());
    registry.registerBeanDefinition("myService",beanDefinition);
    }
    }

    在 registrar 中将 myService 声明到 BeanDefinition 中

  2. 自定义 enable 注解

    1
    2
    3
    4
    5
    6
    7
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Documented
    @Import(MyRegistrar.class)
    public @interface EnableRegistrar {

    }

    通过 import 加载 MyRegistrar

  3. 在 application 类中加上注解并使用@@EnableRegistrar

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @EnableRegistrar
    @SpringBootApplication
    public class RibbonApplication {

    public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(RibbonApplication.class, args);
    Object bean = context.getBean("myService");
    System.out.println(bean);
    }

    }
    1
    com.example.register.MyService@1d6751e3