建立監聽器的兩個步驟
1、事件類繼承ApplicationContextEvent
package com.ysy.listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.stereotype.Component;
/**
* @author shanyangyang
* @date 2020/9/24
*/
@Component
public class Orderevent extends ApplicationContextEvent {
/**
* Create a new ContextStartedEvent.
*
* @param source the {@code ApplicationContext} that the event is raised for
* (must not be {@code null})
*/
public Orderevent(ApplicationContext source) {
super(source);
System.out.println("====訂單事件被初始化了====");
}
public void sout(){
System.out.println("====通知别人訂單被初始化了=====");
}
}
2、注冊監聽器package com.ysy.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author shanyangyang
* @date 2020/9/24
* 注冊lisener,也可以說是觀察者
*/
@Component
public class MyListener implements ApplicationListener<Orderevent> {
@Override public void onApplicationEvent(Orderevent event) {
System.out.println("====監聽器被觸發=====");
System.out.println("====觀察者被調用====");
}
}
3、測試
package com.ysy.test;
import com.ysy.aop.MathCalculator;
import com.ysy.bean.Boss;
import com.ysy.bean.Car;
import com.ysy.config.MainConfigOfAOP;
import com.ysy.config.MainConfigOfAutowired;
import com.ysy.listener.Orderevent;
import org.junit.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author shanyangyang
* @date 2020/6/4
*/
public class IOCTestOfAOP {
@Test
public void test01(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
ApplicationEvent event = context.getBean(Orderevent.class);
context.publishEvent(event);
context.close();
}
}
配置類
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.ysy.listener")
public class MainConfigOfAOP {
}
結果
釋出事件,監聽器方法被調用!
問題:如何在Spring建立所有的bean之後做擴充?
1、利用ContextRefreshEvent
package com.ysy.listener;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
/**
* @author shanyangyang
* @date 2020/9/24
* 監聽容器已經存在的事件
*/
@Component
public class MyListener1 implements ApplicationListener<ContextRefreshedEvent> {
@Override public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("====容器中的bean建立完成了=====");
}
}
2、利用SmartInitializingSington
描述spring事件的原理?
使用的是觀察者模式;
監聽器——觀察者
監聽器需要注冊到主題中去
事件釋出器:publishevent ——主題
調用通知觀察者的實作;