Spring-后置处理器BeanPostProcessor的简单使用和介绍

2年前 (2022) 程序员胖胖胖虎阿
260 0 0

BeanPostProcessor官方定义为工厂钩子,我们也俗称后置处理器。它允许自定义修改新的bean实例,例如检查标记接口或用代理包装它们。应用程序上下文可以在其bean定义中自动检测BeanPostProcessor bean,并将它们应用于随后创建的任何bean。

简单使用

BeanPostProcessor类

public interface BeanPostProcessor {
    @Nullable
    default Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
    @Nullable
    default Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}

既然是接口,那么我们要使用它就必须实现它,我们创建一个SimpleBeanPostProcessor类来实现该接口

@Component
public class SimpleBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessBeforeInitialization - " + bean.getClass().getName() + " - " + beanName);
        return null;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("postProcessAfterInitialization  - " + bean.getClass().getName() + " - " + beanName);
        return null;
    }
}

我们在实现类中只是简单的打印下bean的信息以及beanName

想要后置处理器起作用,那就必须启动spring容器。我们使用AnnotationConfigApplicationContext来启动spring容器。并且在spring中注入一个自定义Bean

@ComponentScan("spring.postProcessor")
@Configuration("spring.postProcessor.run")
public class Run {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Run.class);
        applicationContext.close();
    }

    /**
     * 通过@Bean的方式可以指定initMethod
     * @return
     */
    @Bean(initMethod = "init")
    public MyBean myBean() {
        return new MyBean();
    }
}

MyBean代码如下

@Data
public class MyBean {
    private String beanName;
    private String className;
    public MyBean() {
        System.out.println("MyBean constructor");
    }
    public void init() {
        System.out.println("MyBean is init");
    }
}

运行后结果如下

postProcessBeforeInitialization - spring.postProcessor.Run$$EnhancerBySpringCGLIB$$db1dd68 - spring.postProcessor.run
postProcessAfterInitialization  - spring.postProcessor.Run$$EnhancerBySpringCGLIB$$db1dd68 - spring.postProcessor.run
MyBean constructor
postProcessBeforeInitialization - spring.postProcessor.MyBean - myBean
MyBean is init
postProcessAfterInitialization  - spring.postProcessor.MyBean - myBean

从打打印结果可以看出,后置处理器在bean的构造方法执行之后执行。而且后置处理器的方法postProcessBeforeInitialization和postProcessAfterInitialization分别在Bean的init方法前后执行。并且后置处理器会对spring中所有的bean起作用。

在spring源码类org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory的方法initializeBean中,我们可以看到为什么会这样执行。
Spring-后置处理器BeanPostProcessor的简单使用和介绍
根据以上代码,我们得知,在invokeInitMethods的执行前后,spring会分别调用所有的BeanPostProcessor,执行其中的方法,那么invokeInitMethods的具体内容我们仍需要看下,发现此方法主要作用有两个:1、判断bean是否继承了InitializingBean,如果继承接口,执行afterPropertiesSet()方法,2、获得是否设置了init-method属性,如果设置了,就执行设置的方法

以上就是spring的后置处理器的简单的使用方法以及执行时机。

实战

在 Spring 中,实现注入的方式很多,比如 springboot 的 starter,在自定义的 Configuration 中初始化 ID 生成器的 Bean,业务代码中通过@AutoWired或者@Resource注入即可,开箱即用。这种方式简单直接,但是缺点也是过于简单,缺少了使用方自定义的入口。

考虑一下实际场景,在同一个业务单据中,要保持 ID 的唯一,但是在不同单据中,可以重复。而且,这些算法在生成 ID 的时候,为了保持多线程返回结果唯一,都会锁定共享资源。如果不同业务,并发情景不同,可能低并发的业务被高并发的业务阻塞获取 ID,造成一些性能的损失。所以,我们要考虑将 ID 生成器,根据业务隔离开,这样 springboot 的 starter 就会显得不够灵活了。

根据上面的需求,我们可以分几步实现我们的逻辑:
自定义属性注解,用于判断是否需要注入属性对象
定义 ID 生成器接口、实现类,以及工厂类,工厂类是为了根据定义创建不同的 ID 生成器实现对象
定义 BeanPostProcessor,查找使用自定义注解定义的属性,实现注入

自定义注解

首先自定义一个注解,可以定义一个value属性,作为隔离业务的标识:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface IdGeneratorClient {
    /**
     * ID 生成器名称
     *
     * @return
     */
    String value() default "DEFAULT";
}

定义 ID 生成器

public interface IdGenerator {
    String groupName();

    long nextId();
}

实现 ID 生成器接口,偷懒使用AtomicLong实现自增,同时考虑 ID 生成器是分组的,通过ConcurrentHashMap实现 ID 生成器的持有

class DefaultIdGenerator implements IdGenerator {
    private static final Map<String, AtomicLong> ID_CACHE = new ConcurrentHashMap<>(new HashMap<>());
    private final String groupName;

    DefaultIdGenerator(final String groupName) {
        this.groupName = groupName;
        synchronized (ID_CACHE) {
            ID_CACHE.computeIfAbsent(groupName, key -> new AtomicLong(1));
        }
    }

    @Override
    public String groupName() {
        return this.groupName;
    }

    @Override
    public long nextId() {
        return ID_CACHE.get(this.groupName).getAndIncrement();
    }
}

如前面设计的,我们需要一个工厂类来创建 ID 生成器

public enum IdGeneratorFactory {
    INSTANCE;

    private static final Map<String, IdGenerator> ID_GENERATOR_MAP = new ConcurrentHashMap<>(new HashMap<>());

    public synchronized IdGenerator create(final String groupName) {
        return ID_GENERATOR_MAP.computeIfAbsent(groupName, key -> new DefaultIdGenerator(groupName));
    }
}

定义 BeanPostProcessor

前面都是属于基本操作,这里才是扩展的核心。我们的实现逻辑是:
扫描 bean 的所有属性,然后找到定义了IdGeneratorClient注解的属性
获取注解的value值,作为 ID 生成器的分组标识
使用IdGeneratorFactory这个工厂类生成 ID 生成器实例,这里会返回新建的或已经定义的实例
通过反射将 ID 生成器实例写入 bean

public class IdGeneratorBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
        parseFields(bean);
        return bean;
    }

    private void parseFields(final Object bean) {
        if (bean == null) {
            return;
        }
        Class<?> clazz = bean.getClass();
        parseFields(bean, clazz);

        while (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)) {
            clazz = clazz.getSuperclass();
            parseFields(bean, clazz);
        }
    }

    private void parseFields(final Object bean, Class<?> clazz) {
        if (bean == null || clazz == null) {
            return;
        }

        for (final Field field : clazz.getDeclaredFields()) {
            try {
                final IdGeneratorClient annotation = AnnotationUtils.getAnnotation(field, IdGeneratorClient.class);
                if (annotation == null) {
                    continue;
                }

                final String groupName = annotation.value();

                final Class<?> fieldType = field.getType();
                if (fieldType.equals(IdGenerator.class)) {
                    final IdGenerator idGenerator = IdGeneratorFactory.INSTANCE.create(groupName);
                    invokeSetField(bean, field, idGenerator);
                    continue;
                }

                throw new RuntimeException("未知字段类型无法初始化,bean: " + bean + ",field: " + field);
            } catch (Throwable t) {
                throw new RuntimeException("初始化字段失败,bean=" + bean + ",field=" + field, t);
            }
        }
    }

    private void invokeSetField(final Object bean, final Field field, final Object param) {
        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, bean, param);
    }
}

写一个测试用例,验证我们的实现是否生效

@SpringBootTest
class SpringBeanPostProcessorApplicationTests {
    @IdGeneratorClient
    private IdGenerator defaultIdGenerator;
    @IdGeneratorClient("group1")
    private IdGenerator group1IdGenerator;

    @Test
    void contextLoads() {
        Assert.notNull(defaultIdGenerator, "注入失败");
        System.out.println(defaultIdGenerator.groupName() + " => " + defaultIdGenerator.nextId());

        Assert.notNull(group1IdGenerator, "注入失败");
        for (int i = 0; i < 5; i++) {
            System.out.println(defaultIdGenerator.groupName() + " => " + defaultIdGenerator.nextId());
            System.out.println(group1IdGenerator.groupName() + " => " + group1IdGenerator.nextId());
        }
    }

}

运行结果为:
DEFAULT => 1
DEFAULT => 2
group1 => 1
DEFAULT => 3
group1 => 2
DEFAULT => 4
group1 => 3
DEFAULT => 5
group1 => 4
DEFAULT => 6
group1 => 5
们实现了通过BeanPostProcessor实现自动注入自定义的业务对象,上面的实现还比较简单,有很多可以扩展的地方,比如工厂方法实现,可以借助 SPI 的方式更加灵活的创建 ID 生成器对象。同时,考虑到分布式场景,我们还可以在 ID 生成器实现类中,通过注入 rpc 实例,实现远程 ID 生成逻辑。

玩法无限,就看我们的想象了

转载:
https://segmentfault.com/a/1190000019917321
https://www.jb51.net/article/221734.htm
https://www.iteye.com/blog/zjkilly-738311

相关文章

暂无评论

暂无评论...