欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ImportBeanDefinitionRegistrar方式实现Bean的动态装载

程序员文章站 2022-05-23 10:05:06
...

springboot中有两种方式实现bean的动态装载

  • ImportSelector
  • ImportBeanDefinitionRegistrar

ImportSelector在springboot自动装配原理相关文章中已经介绍过了,这里简单记录下ImportBeanDefinitionRegistrar实现bean的动态装载:1. 首先随便定义一个pojo:

package com.gupaoedu.springcloud.example.demo02;

public class HelloService {

}
  1. 通过实现ImportBeanDefinitionRegistrar 来完成bean的装载:
package com.gupaoedu.springcloud.example.demo02;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClassName(HelloService.class.getName());
        registry.registerBeanDefinition("myhelloService", beanDefinition);
    }
}
  1. 自定义注解EnableMyRegistrar,导入动态装载的配置类MyBeanDefinitionRegistrar
package com.gupaoedu.springcloud.example.demo02;

import org.springframework.context.annotation.Import;
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MyBeanDefinitionRegistrar.class)
public @interface EnableMyRegistrar {
}

  1. springboot启动类类加上自定义注解EnableMyRegistrar
package com.gupaoedu.springcloud.example.springclouduserservice;

import com.gupaoedu.springcloud.example.demo02.EnableGpRegistrara;
import com.gupaoedu.springcloud.example.demo02.EnableMyRegistrar;
import com.gupaoedu.springcloud.example.demo02.HelloService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;

@EnableMyRegistrar
//@EnableGpRegistrara
// 第三方包里面声明的feign接口,不在SpringBootApplication同级目录下,需要手动指定@FeignClient注解扫描包路径
//@EnableFeignClients(basePackages = "com.gupaoedu.example.clients")
@SpringBootApplication
public class SpringCloudUserServiceApplication {

    public static void main(String[] args) {

        ConfigurableApplicationContext contxt=SpringApplication.run(SpringCloudUserServiceApplication.class, args);
        System.out.println(contxt.getBean(HelloService.class));
        System.out.println(contxt.getBean("myhelloService"));
    }

}

运行查看结果
ImportBeanDefinitionRegistrar方式实现Bean的动态装载

相关标签: springboot