ApplicationContextAware接口提供了publishEvent方法,實現了Observe(觀察者)設計模式的傳播機制,實現了對bean的傳播


新增要操作的對象bean

import org.springframework.context.ApplicationEvent;

public class AddEvent extends ApplicationEvent{
	private String name;
	public AddEvent(Object source,String name) {
		super(source);
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

再增加監聽事件

public class AddListener implements ApplicationListener{

	@Override
	public void onApplicationEvent(ApplicationEvent paramE) {
		if(!(paramE instanceof AddEvent)){
			return ;
		}
		
		AddEvent se = (AddEvent) paramE;
		System.out.println("執行方法:"+se.getName());
	}
}

  增加*.xml

<bean id="AddBean" class="com.tdtech.eplatform.gatekeeper.bootstrap.A.Test"></bean>
<bean id="AddListener" class="com.tdtech.eplatform.gatekeeper.bootstrap.A.AddListener"></bean>

增加測試類

public class Test implements ApplicationContextAware{
	  /**
     * 定義Spring上下文對象
     */
    private ApplicationContext m_applicationContext = null;
    public void setApplicationContext(ApplicationContext _applicationContext)
            throws BeansException {
        this.m_applicationContext = _applicationContext;
    }
    
    public void addStudent(String _sStudentName) {
        // 1.構造一個增加學生的事件
        AddEvent aStudentEvent = new AddEvent(
                m_applicationContext, _sStudentName);
        // 2.觸發增加學生事件
        m_applicationContext.publishEvent(aStudentEvent);
    }
    public static void main(String[] args) {
        String[] xmlConfig = new String[] { "classpath:spring/test_spring.xml" };
        // 使用ApplicationContext來初始化系統
        ApplicationContext context = new ClassPathXmlApplicationContext(
                xmlConfig);
        Test studentBean = (Test) context
                .getBean("AddBean");
        studentBean.addStudent("我是第一個學生");
        studentBean.addStudent("第二個學生已經添加");
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM