spring InitializingBean接口

  • spring初始化bena的方式之一 , 其二为 指定init-method方法;
  • 优缺点
	优点 : 实现接口,效率高 , 底层直接强转调用类的方法(AbstractAutowireCapableBeanFactory.invokeInitMethods中执行)
	缺点 : 未解耦
  • 解读
	1.实现InitializingBean接口,重写afterPropertiesSet方法;
	2.在该bean属性注入完毕后执行;
	3.afterPropertiesSet方法先于init-method执行;(invokeInitMethods方法中先判断是否实现InitializingBean接口,有则执行;
	  接着判断是否指定init-method方法,执行init-method)
	4.afterPropertiesSet后于 BeanPostProcess的postProcessBeforeInitialization方法执行;
  • 代码
InitializingBean实现类:

package com.ws.model;
import org.springframework.beans.factory.InitializingBean;
public class User implements InitializingBean {

    private String name;
    private int age;

    public User() {
        System.out.println("User 构造器");
    }

    public User(String name) {
        this(name, 0);
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        System.out.println("set 注入");
        this.age = age;
    }

    public void initMethod() {
        System.out.println("[initMethod] [age]=" + this.age + " [name]=" + name);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet [age]=" + this.age + " [name]=" + name);
    }
}

BeanPostProcessor类:

package com.ws.spring;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

        System.out.println("MyBeanPostProcessor postProcessAfterInitialization   beanName : " +beanName);
        return bean;
    }


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanPostProcessor postProcessBeforeInitialization >>> beanName : " +beanName);
        return bean;
    }
}

配置xml :
   <bean id="user" class="com.ws.model.User" init-method="initMethod">
        <property name="age" value="${age}"></property>
        <property name="name" value="${name}"></property>
    </bean>
  • 测试结果
	User 构造器
	set 注入
	MyBeanPostProcessor postProcessBeforeInitialization >>> beanName : user
	afterPropertiesSet [age]=192 [name]=ws
	[initMethod] [age]=192 [name]=ws
	MyBeanPostProcessor postProcessAfterInitialization   beanName : user
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值