http://hougbin.iteye.com/blog/1273031
問題來源:
有一個bean爲A,一個bean爲B。想要A在容器實例化的時候的一個屬性name賦值爲B的一個方法funB的返回值。
如果只是在A裏單純的寫着:
private B b;
private String name = b.funb();
會報錯說nullpointException,因爲這個時候b還沒被set進來,所以爲null。
解決辦法爲如下代碼,同時學習下spring中 InitializingBean ,對象構造方法 , init-method 的執行順序。
- public class A implements InitializingBean {
- private B b;
- private String name; // = b.funb();
- public void setB(B b) {
- System.out.println("A.setB initialed");
- this.b = b;
- }
- public A() {
- System.out.println("A initialed");
- }
- public void init() {
- System.out.println("init");
- this.name = b.funb();
- }
- @Override
- public String toString() {
- return super.toString() + this.name;
- }
- public void afterPropertiesSet() throws Exception {
- //其實放在這裏也可以
- //this.name = b.funb();
- System.out.println("afterPropertiesSet");
- }
- }
- public class B {
- public String funb() {
- System.out.println("funb");
- return "B.funb";
- }
- public B() {
- System.out.println("B initialed");
- }
- }
spring配置文件
<beans default-autowire="byName">
<bean id="a" class="testspring.A" init-method="init">
</bean>
<bean id="b" class="testspring.B">
</bean>
</beans>
測試代碼:
public static void main(String[] args) {
ApplicationContext context = new FileSystemXmlApplicationContext(
"src/testspring/bean.xml");
A a = (A) context.getBean("a");
System.out.println(a);
}
程序輸出爲:
A initialed
B initialed
A.setB initialed
afterPropertiesSet
init
funb
[email protected]
從這裏看到A的name屬性在bean加載完成的時候也被成功設置爲B的funB方法的返回值了,要點就是用init-method來實現。
加載順序也可以看到爲:
先構造函數——>然後是b的set方法注入——>InitializingBean 的afterPropertiesSet方法——>init-method方法
總結爲:
以下內容是從書中摘錄來的,但是我發現即使摘錄一遍,對其內容的理解也會更加深入!
一、Spring裝配Bean的過程
1. 實例化;
2. 設置屬性值;
3. 如果實現了BeanNameAware接口,調用setBeanName設置Bean的ID或者Name;
4. 如果實現BeanFactoryAware接口,調用setBeanFactory 設置BeanFactory;
5. 如果實現ApplicationContextAware,調用setApplicationContext設置ApplicationContext
6. 調用BeanPostProcessor的預先初始化方法;
7. 調用InitializingBean的afterPropertiesSet()方法;
8. 調用定製init-method方法;
9. 調用BeanPostProcessor的後初始化方法;
Spring容器關閉過程
1. 調用DisposableBean的destroy();
2. 調用定製的destroy-method方法;
一,單一Bean
- 裝載
1. 實例化;
2. 設置屬性值;
3. 如果實現了BeanNameAware接口,調用setBeanName設置Bean的ID或者Name;
4. 如果實現BeanFactoryAware接口,調用setBeanFactory 設置BeanFactory;
5. 如果實現ApplicationContextAware,調用setApplicationContext設置ApplicationContext
6. 調用BeanPostProcessor的預先初始化方法;
7. 調用InitializingBean的afterPropertiesSet()方法;
8. 調用定製init-method方法;
9. 調用BeanPostProcessor的後初始化方法;
- spring容器關閉
1. 調用DisposableBean的destroy();
2. 調用定製的destroy-method方法;
二,多個Bean的先後順序
- 優先加載BeanPostProcessor的實現Bean
- 按Bean文件和Bean的定義順序按bean的裝載順序(即使加載多個spring文件時存在id覆蓋)
- “設置屬性值”(第2步)時,遇到ref,則在“實例化”(第1步)之後先加載ref的id對應的bean
- AbstractFactoryBean的子類,在第6步之後,會調用createInstance方法,之後會調用getObjectType方法
- BeanFactoryUtils類也會改變Bean的加載順序