Spring 之 BeanPostProcessor

将实现了BeanPostProcessor接口的类定义为bean,将拥有预处理和后处理bean的能力。

Example:

public class ThymeleafSecurityDialectProcessor implements BeanPostProcessor {

    private static final Logger logger = LoggerFactory.getLogger(ThymeleafSecurityDialectProcessor.class);
    private static boolean needAddDialect = false;

    static {
        boolean springTemplatePresent = ClassUtils.isPresent("org.thymeleaf.spring4.SpringTemplateEngine", ThymeleafSecurityDialectProcessor.class.getClassLoader());
        boolean springTemplateInterfacePresent = ClassUtils.isPresent("org.thymeleaf.templateresolver.ITemplateResolver", ThymeleafSecurityDialectProcessor.class.getClassLoader());
        needAddDialect = springTemplateInterfacePresent && springTemplatePresent;
    }

    @Override
    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        return o;
    }

    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        if(needAddDialect && o instanceof SpringTemplateEngine){

            SpringTemplateEngine engine = (SpringTemplateEngine)o;
            boolean exist = engine.getDialects().stream()
                    .anyMatch(it->it instanceof SpringSecurityDialect);
            if(!exist){
                logger.info("add SpringSecurityDialect for {}", engine.toString());
                engine.addDialect(new SpringSecurityDialect());
            }else{
                logger.info("SpringSecurityDialect already exist for {}", engine.toString());
            }
        }
        return o;
    }
}

这里演示了对bean进行了后处理。

你可能感兴趣的:(Spring)