spring中创建bean后,我们在完成对一个bean的操作后,我们希望把运行后的bean结果同步传递给另一个bean。
首先创建一个消息的载体,这个bean需要继承ApplicationEvent类。
/**
* Created by lengshan on 2018/3/14 0014.
*
* 这个bean继承ApplicationEvent,通过事件发布来传递消息,是消息传递的载体
*/
public class DemoBean extends ApplicationEvent{
private static final long serialVersionUID = 1L;
private String recvMessage;
public DemoBean (Object source,String recvMessage){
super(source);
this.recvMessage = recvMessage;
}
public String getRecvMessage() {
return recvMessage;
}
public void setRecvMessage(String recvMessage) {
this.recvMessage = recvMessage;
}
}
创建事件监听类,这个类需要继承ApplicationListener类,用于监听并接收消息载体传递的信息
/**
* Created by lengshan on 2018/3/14 0014.
*
* 传入类泛型参数为消息的载体DemoBean,实现接口ApplicationListener注册为监听类,并且实现他的方法onApplicationEvent
* 用于接收载体传过来的数据
*/
@Component
public class DemoEventListener implements ApplicationListener<DemoBean> {
/**
*
* 使用这个方法onApplicationEvent来接收传递的消息
*/
public void onApplicationEvent(DemoBean demoBean){
String msg = demoBean.getRecvMessage();
System.out.println("我DemoEventListener接收到了DemoEvent传递的消息"+msg);
}
}
创建事件发布类
/**
* Created by lengshan on 2018/3/14 0014.
*/
//bean的声明
@Component
public class DemoEventPublish {
/**
* 使用ApplicationContext类来进行发布消息
*/
//bean的注入
@Autowired
ApplicationContext applicationContext;
public void publish(String msg){
applicationContext.publishEvent(new DemoBean(this,msg));
}
}
配置类
/**
* Created by lengsdhan on 2018/3/14 0014.
*/
@Configuration
@ComponentScan("com.example.demo")
public class MyConfig {
}
main函数
@SpringBootApplication
public class DemoSpringeventApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringeventApplication.class, args);
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
DemoEventPublish demoEventPublish = context.getBean(DemoEventPublish.class);
demoEventPublish.publish("哈哈哈!!");
context.close();
}
}
运行结果
我DemoEventListener接收到了DemoEvent传递的消息哈哈哈!!
这里记一下我写的时候遇到的问题,我在消息载体事件Demobean里加入了标签@Component,这样在事件发布类里@Autowired注入载体事件bean后,运行就会报错org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoBean' defined in file 。这个错误产生的原因我现在还是不能理解,希望大神看到可以帮我解决一下。
参考:《Java EE开发的颠覆者 spring boot实战》