springboot中ApplicationEventPublisher的使用案例
时间: 2024-06-13 20:06:44 浏览: 17
在Spring Boot中,我们可以使用ApplicationEventPublisher来发布自定义事件。下面是一个简单的使用案例:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
@Component
public class MyEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEvent(final String message) {
System.out.println("Publishing custom event. ");
MyEvent customSpringEvent = new MyEvent(this, message);
applicationEventPublisher.publishEvent(customSpringEvent);
}
}
```
在上面的代码中,我们首先注入了ApplicationEventPublisher,然后定义了一个publishEvent方法,该方法接受一个字符串参数message。在该方法中,我们创建了一个自定义事件MyEvent,并使用ApplicationEventPublisher发布了该事件。
下面是自定义事件MyEvent的定义:
```java
import org.springframework.context.ApplicationEvent;
public class MyEvent extends ApplicationEvent {
private String message;
public MyEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
```
在上面的代码中,我们继承了ApplicationEvent,并添加了一个message属性和相应的getter方法。
最后,我们需要定义一个事件监听器来处理自定义事件。下面是一个简单的事件监听器:
```java
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class MyEventListener {
@EventListener
public void onApplicationEvent(MyEvent event) {
System.out.println("Received spring custom event - " + event.getMessage());
}
}
```
在上面的代码中,我们使用@EventListener注解来标记onApplicationEvent方法,该方法接受一个MyEvent参数。当MyEvent事件被发布时,该方法将被调用,并输出事件的message属性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)