ApplicatonContext注册BeanFactoryPostProcessor处理器

1、pojo

package com.wenpu.bean;

public class Car {
 
 public Car(){
  System.out.println("invoke default constructor");
 }

 private String brandName;

 public String getBrandName() {
  return brandName;
 }

 public void setBrandName(String brandName) {
  this.brandName = brandName;
  System.out.println("invoke setter method");
 }
}

2、实现BeanFactoryPostProcessor处理器

package com.wenpu.processor;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor{

 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory bf)
   throws BeansException {
  BeanDefinition bd=(BeanDefinition)bf.getBeanDefinition("car");
  bd.getPropertyValues().add("brandName", "奥迪");
  System.out.println("invoke BeanFactoryPostProcessor.postProcessBeanFactory");
 }

}

3、bean配置

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

 <!-- pojo定义 -->

 <bean id="car" class="com.wenpu.bean.Car" p:brandName="红旗"/>

<!-- BeanFactoryPostProcessor处理器,ApplicationContext会自动注册该处理器 -->
 <bean id="myBeanFactoryPostProcessor" class="com.wenpu.processor.MyBeanFactoryPostProcessor"/>
</beans>                  

4、测试类

package com.wenpu.test;

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

import com.wenpu.bean.Car;

public class BeanCycleTest {

 public static void main(String[] args) {
  ApplicationContext context=new ClassPathXmlApplicationContext("BeanCycleInBeanFactory-context.xml");
  Car car=(Car)context.getBean("car");
  System.out.println(car.getBrandName());
 }
}

5、输出结果:

invoke BeanFactoryPostProcessor.postProcessBeanFactory

invoke default constructor
invoke setter method
奥迪

6、总结:从结果看brandName由"红旗"变为了"奥迪".

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值