方式一: 手工向ApplicationContext中添加监听器
定义事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package xyz.xinbaojian.admin.event;
import lombok.Data; import org.springframework.context.ApplicationEvent;
@Data public class BlackListEvent extends ApplicationEvent {
private String address;
public BlackListEvent(Object source, String address) { super(source); this.address = address; } }
|
定义监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| package xyz.xinbaojian.admin.event;
import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener;
@Slf4j public class BlackListListener implements ApplicationListener<BlackListEvent> {
@Override public void onApplicationEvent(BlackListEvent event) { log.info(String.format("监听到BlackListEvent事件: %s", event.getAddress())); } }
|
注册监听器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package xyz.xinbaojian;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; import xyz.xinbaojian.admin.event.BlackListListener;
@SpringBootApplication(scanBasePackages="xyz.xinbaojian") public class Application {
public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(Application.class,args); context.addApplicationListener(new BlackListListener()); } }
|
方式二: 将监听器装载入spring容器
事件定义,定义监听器同上.
注册监听器使用注解 @Component
把监听器注入到Spring容器中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package xyz.xinbaojian.admin.event;
import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component;
@Slf4j @Component public class BlackListListener implements ApplicationListener<BlackListEvent> {
@Override public void onApplicationEvent(BlackListEvent event) { log.info(String.format("监听到BlackListEvent事件: %s", event.getAddress())); } }
|
方式三: 在application.properties中配置监听器
事件定义,定义监听器同上.
注册监听器在application.properties中配置监听
context.listener.classes=xyz.xinbaojian.admin.event.BlackListListener
方式四: 通过@EventListener注解实现事件监听
事件定义,定义监听器同上.
注册监听器无需实现ApplicationListener接口,使用@EventListener装饰具体方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| package xyz.xinbaojian.admin.event;
import lombok.extern.slf4j.Slf4j; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component;
@Slf4j @Component public class BlackListListener {
@EventListener public void onApplicationEvent(BlackListEvent event) { log.info(String.format("监听到BlackListEvent事件: %s", event.getAddress())); } }
|