有关Spirng ioc的BeanPostProcessor接口案例

关于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配置:


<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进行初始化操作或者是某些校验的时候,可以进行相应的拦截操作。

你可能感兴趣的:(java,spring)