Spring 的 BeanPostProcessor 接口使用示例

        

目录

1、BeanPostProcessor 接口使用示例

2、使用 Java 代码配置 bean 定义


        本节主要介绍在《Spring生命周期》一节提到的 BeanPostProcessor 接口。

        BeanPostProcessor 接口也被称为 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;
    }
}

        postProcessBeforeInitialization 在 Bean 实例化、依赖注入后,初始化前调用, postProcessAfterInitialization 在 Bean 初始化成后调用。

        当需要添加多个后置处理器实现类时,默认情况下 Spring 容器会根据后置处理器的定义顺序来依次调用。也可以通过实现 Ordered 接口的 getOrder 方法指定后置处理器的执行顺序。该方法返回值为整数,默认值为 0,值越大优先级越低。

1、BeanPostProcessor 接口使用示例

        下面使用 IntelliJ IDEA 演示 BeanPostProcessor 接口的用法,步骤如下:

  1. 创建 Spring 项目,并在 src 目录下创建com.spring_learn包。
  2. 在 spring_learn 包下创建 HelloWorld、InitHelloWorld_1、InitHelloWorld_2 和 MainApp 类。
  3. 在 src 目录下创建 Spring 配置文件 Beans.xml (附:Java代码配置方式)。
  4. 运行 Spring 项目。

        HelloWorld 类代码如下。

public class HelloWorld {

    private String message;

    public void setMessage(String message) {
        this.message = message;
    }

    public String getMessage() {
        return "Message : " + message;
    }

    public void init() {
        // this.setMessage("Hello Message ...");
        System.out.println("HelloWorld Bean正在初始化");
    }

    public void destroy() {
        System.out.println("HelloWorld Bean将要被销毁");
    }
}

        InitHelloWorld_1 类代码如下:

public class InitHelloWorld_1 implements BeanPostProcessor, Ordered {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if("helloWorld".equals(beanName)){
            System.out.println("A Before : " + beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("helloWorld".equals(beanName)){
            System.out.println("A After : " + beanName);
        }
        return bean;
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

        需要注意的是,postProcessBeforeInitialization 和 postProcessAfterInitialization 方法返回值不能为 null,否则会报空指针异常或者通过 getBean() 方法获取不到 Bean 实例对象,因为后置处理器从Spring IoC 容器中取出 Bean 实例对象后没有再次放回到 IoC 容器中创建的 bean 后置处理器,它会作用到容器中的每一个Bean上

        InitHelloWorld_2 的代码如下:

public class InitHelloWorld_2 implements BeanPostProcessor, Ordered {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if("helloWorld".equals(beanName)){
            System.out.println("B Before : " + beanName);
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("helloWorld".equals(beanName)){
            System.out.println("B After : " + beanName);
        }
        return bean;
    }

    @Override
    public int getOrder() {
        return 2;
    }
}

        Beans.xml 代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="helloWorld" class="com.swadian.spring_learn.HelloWorld"
          init-method="init" destroy-method="destroy">
        <property name="message" value="Hello beans.xml..." />
    </bean>

    <!-- 注册处理器 -->
    <bean class="com.swadian.spring_learn.InitHelloWorld_1" />
    <bean class="com.swadian.spring_learn.InitHelloWorld_2" />
</beans>

        MainApp 类代码如下:

public class MainApp {
    public static void main(String[] args) {
        //注解方式
        //AbstractApplicationContext context = new AnnotationConfigApplicationContext(HelloWorldConfiguration.class);
        //xml方式
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
        HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
        System.out.println(obj.getMessage());
        //确保正常关闭,并且调用相关的 destroy 方法
        context.registerShutdownHook();
    }
}

        运行结果如下:

        由运行结果可以看出,postProcessBeforeInitialization 方法是在 Bean 实例化后,初始化回调方法前执行的。而 postProcessAfterInitialization 方法是在初始化回调方法后执行的。另外, getOrder 方法返回值越大,优先级越低,所以 InitHelloWorld_1 先执行。

2、使用 Java 代码配置 bean 定义

        从Spring3.0,@Configuration用于定义配置类,可替换xml配置文件,被注解的类内部包含有一个或多个被 @Bean 注解的工厂方法,这些方法将被 Spring 容器扫描,并用于构建 bean 定义。

@Configuration
public class HelloWorldConfiguration {

    String message = "Hello ConfigurationMessage ...";

    // @Bean注解注册bean,同时可以指定初始化和销毁方法
    @Bean(name = "helloWorld", initMethod = "init", destroyMethod = "destroy")
    public HelloWorld getHelloWorld() {
        HelloWorld helloWorld = new HelloWorld();
        helloWorld.setMessage(message);
        return helloWorld;
    }

    @Bean
    public InitHelloWorld_1 initHelloWorld_1() {
        return new InitHelloWorld_1();
    }

    @Bean
    public InitHelloWorld_2 initHelloWorld_2() {
        return new InitHelloWorld_2();
    }

}

        至此,Spring bean 后置处理器的简单应用介绍完毕。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

swadian2008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值