通过InitializingBean在bean对象初始化完成执行代码

在使用spring一段时间后,某些特殊场景,你总是希望在bean对象初始化完后执行一段代码,来通知其它对象或者对bean对象进行再加工。本文实现了这种代码demo。

  • 下面是代码demo

实现已car类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.zw.dubbo.initializing.bean;

import org.springframework.beans.factory.InitializingBean;

public class Car implements InitializingBean {

private String name;

@Override
public void afterPropertiesSet() throws Exception {
System.out.println("所有属性设置完了");
System.out.println("this car name is " + name);
}

public String getName() {
return name;
}

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

InitializingBean接口中只有一个方法,它会在bean对象属性设置完成后进行回调。

下面把Car对象注入到spring容器中去, AfterPropertiesSet.xml

1
2
3
4
5
6
7
8
9
<?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-4.3.xsd">

<bean id="car" class="com.zw.dubbo.initializing.bean.Car">
<property name="name" value="风一样的汽车"/>
</bean>
</beans>

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.zw.dubbo.initializing.bean;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAfterPropertiesSet {

public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"classpath:AfterPropertiesSet.xml"});
context.start();
System.out.println("context初始化完成了");
Car car = (Car) context.getBean("car");
System.out.println("the car:" + car.getName());
}

}

执行结果

1
2
3
4
5
10:49:48.485 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'car'
所有属性设置完了
this car name is 风一样的汽车
context初始化完成了
the car:风一样的汽车