java springboot监听事件和处理事件
在Spring Boot中,你可以使用@EventListener
注解来监听特定的事件,并处理它们。以下是一个简单的例子:
首先,定义一个事件类:
public class MyEvent {
private String message;
public MyEvent(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
然后,创建一个事件监听器:
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
@Component
public class MyEventListener {
@EventListener
public void handleMyEvent(MyEvent event) {
System.out.println("Event received: " + event.getMessage());
}
}
最后,在某个地方发布这个事件:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
@Service
public class MyService {
@Autowired
private ApplicationEventPublisher publisher;
public void doSomething() {
// ... do something
publisher.publishEvent(new MyEvent("Action performed"));
}
}
当你调用doSomething()
方法时,MyEvent
事件被发布,MyEventListener
的handleMyEvent
方法会被调用来处理这个事件。
评论已关闭