有关Spirng ioc的BeanPostProcessor接口案例

11 篇文章 1 订阅

关于spring里面的BeanPostProcessor接口的调用,每一个实现了该接口的类,一旦被注入到了spring容器里面之后,那么spring容器在进行相应的类实例化的时候,会对每一个类进行拦截,判断该类是否有实现该接口。
案例代码:
student

package com.sise.lh.lab01;

/**
 * 作者:idea
 * 时间:2017/9/14
 * 使用说明:学生bean
 */
public class Student {
    private int age;
    private String name;

    public void init(){
        this.age=18;
    }
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
package com.sise.lh.lab01;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * 作者:idea
 * 时间:2017/9/28
 * 使用说明:只要有一个bean实现了这个接口,就一定会将所有的bean都做一次拦截
 */
public class StudentCheck implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if(beanName.equals("student")) {
            Student student= (Student) bean;
            student.setAge(18);
            student.setName("idea");
            System.out.println("this is postProcessBeforeInitialization");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String s) throws BeansException {
        System.out.println("this is postProcessAfterInitialization");
        return bean;
    }
}

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.xsd">
    <bean id="student" class="com.sise.lh.lab01.Student"></bean>
    <bean id="studentCheck" class="com.sise.lh.lab01.StudentCheck"></bean>
</beans>

案例测试:

package com.sise.lh.lab01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 作者:idea
 * 时间:2017/9/28
 * 使用说明:案例测试
 */
public class DemoTest {
    public static void main(String[] args) {
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("lab01/spring-config01.xml");
        Student student= (Student) applicationContext.getBean("student");
        System.out.println(student.getAge());
        System.out.println(student.getName());
    }
}

控制台输出结果:

this is postProcessBeforeInitialization
this is postProcessAfterInitialization
18
idea

使用上述的思路,我们在对于相应的bean进行初始化操作或者是某些校验的时候,可以进行相应的拦截操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值