Spring源碼解讀以及Spring整體結構淺析

  • BeanFactory結構圖
  • Spring容器啓動過程
  • Bean實例化過程

 

1、bean實現Aware接口的意義(圖中檢查Aware相關接口並設置相關依賴)

package com.anotation.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class Dog implements ApplicationContextAware {

	private String name;

	//10公;20母
	private Integer sex;
	
	private ApplicationContext applicationContext;

	public String getName() {
		return name;
	}

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

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public Dog(){
		System.out.println("dog constructor...");
	}
	
	//對象創建並賦值之後調用
	@PostConstruct
	public void init(){
		System.out.println("Dog....@PostConstruct...");
	}
	
	//容器移除對象之前調用
	@PreDestroy
	public void detory(){
		System.out.println("Dog....@PreDestroy...");
	}

	//實現ApplicationContextAware接口,並重寫他的setApplicationContext()方法,可以讓當前對象擁有容器的ApplicationContext引用
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	@Override
	public String toString() {
		return "Dog{" + "name='" + name + '\'' + ", sex=" + sex + '}';
	}
}

2、實現BeanPostProcessor的作用:他的兩個方法都傳入了對象實例的引用,這爲我們擴展容器的對象實例化過程中的行爲提供了極大的便利,我們幾乎可以對傳入的對象實例做任何操作

package com.anotation.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 *
 * 創建一個BeanPost類,實現BeanPostProcessor接口。
 * 在其postProcessAfterInitialization()方法中修改通過參數傳入的受管Bean,然後返回。
 * 由於它處理容器中的每一個Bean,因此在修改前,應判斷Bean是否爲我們要處理的Bean。
 * 可以通過傳入Bean的類型判定,也可以通過傳入Bean的名字判定
 *
 * @author zhengchao
 */
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

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

        System.out.println("postProcessBeforeInitialization..." + beanName + "=>" + bean);
        System.out.println("BeanPostProcessor.postProcessAfterInitialization 正在預處理!");
        //過濾特定類型的bean來修改bean的屬性或其爲其進行增強(AOP就是基於此原理)
        if ((bean instanceof Dog)){
            Dog dog = (Dog) bean;
            dog.setName("范冰冰");
            dog.setSex(20);
            return bean;
        }
        return bean;
    }

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

 

to be continue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章