1.Spring事件用于满足Bean之间的通信关系;
2.Spring事件中的角色:Event事件,事件发布者,事件监听者
3.示例工程
Event事件类
public class DemoEvent extends ApplicationEvent{
/**
* @author Tango
*/
private static final long serialVersionUID = 1L;
private String msg;
public DemoEvent(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 DemoPublisher {
@Autowired
ApplicationContext applicationContext;
public void publish(String msg) {
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
事件监听者:
@Componentpublic class DemoListener implements ApplicationListener{
@Override
public void onApplicationEvent(DemoEvent event) {
String msg=event.getMsg();
System.out.println("**************************事件的消息被打印了!************************"+msg);
}
}
应用配置类
@Configuration
@ComponentScan("com.tango.redis")
public class DemoPublisherConfig {
}
应用启动类
@SpringBootApplication
public class SpringRedisApplication {
public static void main(String[] args) {
/*SpringApplication.run(SpringRedisApplication.class, args);*/
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(DemoPublisherConfig.class);
DemoPublisher publisher = context.getBean(DemoPublisher.class);
publisher.publish("新年快乐");
}
}
应用结果:
14:13:33.995 [main] INFO org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
14:13:33.995 [main] DEBUG org.springframework.jmx.export.annotation.AnnotationMBeanExporter - Autodetecting user-defined JMX MBeans
14:13:34.011 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@1bda97b]
14:13:34.011 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
14:13:34.011 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor'
14:13:34.011 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Found key 'spring.liveBeansView.mbeanDomain' in PropertySource 'systemProperties' with value of type String
14:13:34.011 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'demoPublisher'
14:13:34.011 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'demoListener'
**************************事件的消息被打印了!************************新年快乐
网友评论