zoukankan      html  css  js  c++  java
  • Spring中的事件机制

    Spring中的事件机制

    Spring对事件机制也提供了支持,一个事件被发布后,被对应的监听器监听到,执行对应方法。

    Spring内已经提供了许多事件,ApplicationEvent可以说是Spring事件的顶级父类。

    ApplicationListener 是监听器的顶级接口,事件被触发后,onApplicationEvent方法就会执行。

    如监听容器刷新的一个监听器:

    @Component
    public class AppLister implements ApplicationListener<ApplicationEvent> {
    
    	@Override
    	public void onApplicationEvent(ApplicationEvent event) {
    		// TODO Auto-generated method stub
    		if(event instanceof ContextRefreshedEvent) {
    			System.out.println("监听到app启动");
    		}
    		
    	}
    
    }
    

    自定义事件

    自定义事件需要满足以下条件:
    	1、自定义一个事件类,继承Spring中的事件类。
    	2、自定义一个监听器,实现Spring中的监听器以及对应方法。
    	3、发布事件
    

    事件类

    public class MyEvent extends ApplicationEvent{
    
    
    	private String msg;
    
    	public MyEvent(Object source, String msg) {
    		super(source);
    		this.msg = msg;
    	}
    
    	public String getMsg() {
    		return msg;
    	}
    
    	public void setMsg(String msg) {
    		this.msg = msg;
    	}
    
    
    
    }
    
    

    监听器

    @Component
    public class MyLister  implements ApplicationListener<MyEvent>{
    
    
    	public void onApplicationEvent(MyEvent myEvent) {
    		String msg = myEvent.getMsg();
    		System.out.println("监听到消息: "+msg);
    	}
    }
    

    测试

    @Configuration
    @ComponentScan("event")//扫描所有bean
    public class EventConfig {
    	
    }
    
    //发布者,内部调用Spring容器,可以不实现,直接使用容器即可
    @Component
    public class MyPublisher {
    	@Autowired
    	ApplicationContext context;
    
    	public void publish(String msg) {
    		context.publishEvent(new MyEvent(this, msg));
    	}
    }
    
    
    //测试类
    public class EventTest {
    
        ApplicationContext context;
    
        @Test
        public void test(){
            context=new AnnotationConfigApplicationContext(EventConfig.class);
            MyPublisher publisher = context.getBean(MyPublisher.class);
            publisher.publish("Hello msg");
    
        }
    
        @Test
        public void test2(){
            context=new AnnotationConfigApplicationContext(EventConfig.class);
            context.publishEvent(new MyEvent(this,"ok ok"));
    
        }
    
    }
    
    
    监听到消息: ok ok
    
  • 相关阅读:
    【转】 上海交大ACM队长建议
    好资源
    待做
    分治思想
    周末看的东西
    [UVa11988] Broken Keyboard (a.k.a. Beiju Text)
    UVa 题目分类
    [UVa11729] Commando War
    [LA3135] Arugus
    [UVa11995] I Can Guess the Data Structure!
  • 原文地址:https://www.cnblogs.com/cgl-dong/p/13844802.html
Copyright © 2011-2022 走看看