spring时间监听器示例
时间: 2023-07-26 21:40:49 浏览: 107
下面是一个简单的Spring时间监听器示例:
首先,定义一个事件类, 例如:
```java
public class CustomEvent extends ApplicationEvent {
private String message;
public CustomEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getMessage() {
return message;
}
}
```
然后,定义一个事件监听器类,例如:
```java
public class CustomEventListener implements ApplicationListener<CustomEvent> {
@Override
public void onApplicationEvent(CustomEvent event) {
System.out.println("Received custom event - " + event.getMessage());
}
}
```
接下来,在Spring配置文件中注册事件监听器:
```xml
<bean id="customEventListener" class="com.example.CustomEventListener"/>
```
最后,在需要触发事件的地方,注入ApplicationEventPublisher并发布事件:
```java
@Autowired
private ApplicationEventPublisher publisher;
public void doSomethingAndPublishEvent(String message) {
// do something
publisher.publishEvent(new CustomEvent(this, message));
}
```
当CustomEvent被发布时,CustomEventListener中的onApplicationEvent方法将会被调用。
阅读全文