zoukankan      html  css  js  c++  java
  • Spring Bean后置处理器

    本例子源于:W3CSchool,在此作记录

    Bean 后置处理器允许在调用初始化方法前后对 Bean 进行额外的处理。

    BeanPostProcessor 接口定义回调方法,你可以实现该方法来提供自己的实例化逻辑,依赖解析逻辑等。你也可以在 Spring 容器通过插入一个或多个 BeanPostProcessor 的实现来完成实例化,配置和初始化一个bean之后实现一些自定义逻辑回调方法。

    你可以配置多个 BeanPostProcessor 接口,通过设置 BeanPostProcessor 实现的 Ordered 接口提供的 order 属性来控制这些 BeanPostProcessor 接口的执行顺序。

    BeanPostProcessor 可以对 bean(或对象)实例进行操作,这意味着 Spring IoC 容器实例化一个 bean 实例,然后 BeanPostProcessor 接口进行它们的工作。

    ApplicationContext 会自动检测由 BeanPostProcessor 接口的实现定义的 bean,注册这些 bean 为后置处理器,然后通过在容器中创建 bean,在适当的时候调用它

    在你自定义的的BeanPostProcessor 接口实现类中,要实现以下的两个抽象方法BeanPostProcessor.postProcessBeforeInitialization(Object, String) 和BeanPostProcessor.postProcessAfterInitialization(Object, String) 和,注意命名要准确

    否则会出现: “ The type InitHelloWorld must implement the inherited abstract method BeanPostProcessor.postProcessBeforeInitialization(Object, String) ”之类的错误

    相对于上个例子,在原来的基础上新增一个BeanPostProcessor 接口实现类,在xml配置文件中添加该实现类对应的bean

    BeanPostProcessor 接口实现类如下:

    package com.how2java.w3cschool.beanlife;
    
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class InitHelloWorld implements BeanPostProcessor{
        public Object postProcessBeforeInitialization(Object bean,String beanName) {
            System.out.println("BeforeInitialization:"+beanName);
            return bean;  // you can return any other object as well
        }
        
        public Object postProcessAfterInitialization(Object bean,String beanName) {
            System.out.println("AfterInitialization:"+beanName);
            return bean;  // you can return any other object as well
        }
    }

    xml配置文件新增如下内容:

    <bean class = "com.how2java.w3cschool.beanlife.InitHelloWorld"></bean>

    输出的结果如下:

  • 相关阅读:
    (转)性能测试---并发用户理解
    (转)基于DDD的现代ASP.NET开发框架--ABP分层架构
    (转)Web自动化测试中的接口测试
    (转) 一致性Hash算法在Memcached中的应用
    Memcached工作原理及常见问题
    Memcached介绍及相关知识
    .net 面试题总结
    使用IDEA工具配置和运行vue项目(详细其中的坑)
    关于伪分布zookeeper集群启动出错(Error contacting service. It is probably not running.)
    常用查找和排序
  • 原文地址:https://www.cnblogs.com/Guhongying/p/10594631.html
Copyright © 2011-2022 走看看