菜单

Administrator
Administrator
发布于 2023-11-04 / 39 阅读 / 0 评论 / 0 点赞

自定义加载外部bean

  • 继承BeanDefinitionRegistryPostProcessor

@Component
public class BeanCustomLoadHelper implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    public static String beanName="";
    @SneakyThrows
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        String value = applicationContext.getEnvironment().getProperty("xxxx");
        if (condition(value)) {
            AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition)registry.getBeanDefinition(beanName);
            registry.removeBeanDefinition(beanName);
            AnnotatedGenericBeanDefinition customerDefinition = new AnnotatedGenericBeanDefinition(beanDefinition.getMetadata());
            BeanUtil.copyProperties(beanDefinition,customerDefinition,"beanClass", "originatingBeanDefinition");
            customerDefinition.setBeanClassName(BeanConfig.class.getName());
            customerDefinition.resolveBeanClass(Thread.currentThread().getContextClassLoader());
            registry.registerBeanDefinition(beanName,customerDefinition);
        }
    }

    private Boolean condition(String value) {
        return true;
    }


    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}
  • 直接同包路径,同类名,进行替换:这种方式简单粗暴,前提必须是同包路径,同类名。可以直接覆盖掉jar包中的类,Spring项目会优先加载自定义的类。

  • 继承要替换的类,在配置类中进行配置,返回其子类:首先创建一个新的bean,继承需要被重写的bean。然后在启动类中排除父类。最后在配置类中创建子类。

import org.springframework.context.annotation.ComponentScan;

@Component
@ComponentScan(excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = BeanConfig.class)
})
public class Config {

}


评论