自定义spring扫描类加载自己需要的类

1、spring容器对外接口

BeanDefinitionRegistryPostProcessor和扫描类ClassPathBeanDefinitionScanner

2、实现该接口的主要方法:

postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)

3、demo

public class DemoScannerConfigurer
    implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware, BeanNameAware {

  

    private final String filterName="AbstractSubscribeMessageTemplate";

    private String basePackage;

    private List interfaceTypes = new LinkedList<>();

    private Set templateIdSets = new HashSet<>();
    @Override
    public void setBeanName(String name) {

    }

    public void afterPropertiesSet() {

        for (String className : interfaceTypes) {
            try {
                Class interfaceType = (Class)Class
                    .forName(className);

                AbstractSubscribeMessageTemplate instance = interfaceType.getConstructor(new Class[0]).newInstance(new Object[0]);

                if(templateIdSets.contains(instance.getTemplateId())){

                    throw new RuntimeException("模板Id[" + instance.getTemplateId() + "],class[" + instance.getClass() + "],已经存在一个相同id的模板。");
                }
                templateIdSets.add(instance.getTemplateId());
                SubscribeMessageTemplateFactory.addTemplate(MessageTemplateMetadata.of(instance.getTemplateId(), instance.getTemplateName(), instance.getMessageTemplateType()));

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        logger.info("weChat.message.Template.size|{}", SubscribeMessageTemplateFactory.getTemplates().size());

    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(registry, false);

        scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> {

            ClassMetadata classMetadata = metadataReader.getClassMetadata();

            if (!classMetadata.isInterface() && classMetadata.getSuperClassName().endsWith(filterName)) {

                interfaceTypes.add(classMetadata.getClassName());
            }

            return false;
        });
        scanner.scan(this.basePackage);
        afterPropertiesSet();
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

    }

    public String getBasePackage() {
        return basePackage;
    }

    public void setBasePackage(String basePackage) {
        this.basePackage = basePackage;
    }
}

px:spring/springboot扩展点介绍

掌握这些 SpringBoot 启动扩展点,已经超过 90% 的人了_肥肥技术宅的博客-CSDN博客

你可能感兴趣的:(spring,java,后端)