zoukankan      html  css  js  c++  java
  • 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("第二个学生已经添加");
        }
    }
    

      

  • 相关阅读:
    201706120024 编译原理第一次作业
    P2014 选课 题解(树形DP)
    基础算法·二分答案
    P4285 [SHOI2008]汉诺塔 题解 (乱搞)
    2018.12-2019.1 TO-DO LIST
    记录一枚蒟蒻的成长(持续更新)
    P3796 【模板】AC自动机(加强版) 题解(Aho-Corasick Automation)
    BuaacodingT651 我知道你不知道圣诞节做什么 题解(逻辑)
    P2766 最长不下降子序列问题 题解(网络流)
    P2516 [HAOI2010]最长公共子序列 题解(LCS)
  • 原文地址:https://www.cnblogs.com/sg9527/p/7687662.html
Copyright © 2011-2022 走看看