我们知道,在spring启动的过程中,会生成很多的监听器,监听整个spring容器的生命周期。那么,我们想要生成自己的listener需要怎么做呢?今天,就给大家带来spring boot实现监听器的两种方式。

自定义事件

自定义事件XiaoAMaCreatedEvent继承ApplicationEvent类

/**
 * [说明]
 *
 * @author xiaoama
 */
public class XiaoAMaCreatedEvent extends ApplicationEvent {

    private String message;

    public XiaoAMaCreatedEvent(Object source) {
        super(source);
    }


    public XiaoAMaCreatedEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

自定义监听器-listener

今天给大家带来两种自定义监听器的创建方式。

方式一

实现ApplicationListener接口,泛型参数传入我们自定义的event事件

/**
 * [说明]
 *
 * @author xiaoama
 */
@Component
public class XiaoAMaListener implements ApplicationListener<XiaoAMaCreatedEvent> {

    @Override
    public void onApplicationEvent(XiaoAMaCreatedEvent event) {
        String message = event.getMessage();
        System.out.println("接受到acceount创建,正在发送创建信息:"+message);
    }
}

方式二

自定义listener类,提供监听的方法processAccountCreatedEvent(方法名可以自定义),接受一个自定义的event事件作为参数,同时添加注解 @EventListener

/**
 * [说明]
 *
 * @author xiaoama
 */
@Component
public class XiaoAMaListener {

    @EventListener
    public void processAccountCreatedEvent(XiaoAMaCreatedEvent event){
        String message = event.getMessage();
        System.out.println("接受到acceount创建,正在发送创建信息:"+message);
    }
}

发布监听事件

可以通过应用上下文applicationcontext的publishEvent方法发布一个监听事件,在启动日志中就能看到我们的监听器的打印日志

@SpringBootApplication
public class App 
{
    public static void main( String[] args )

    {
        //创建一个可执行的spring应用程序
        SpringApplication application = new SpringApplication(App.class);

        ConfigurableApplicationContext context =application.run(args);
  
        context.publishEvent(new XiaoAMaCreatedEvent(new Object(),"create success"));

    }
}

监听器打印日志

2020-11-17 11:02:43.689 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8099 (http) with context path ''
2020-11-17 11:02:43.693 [main] INFO  org.example.App - Started App in 9.453 seconds (JVM running for 12.396)
接受到acceount创建,正在发送创建信息:create success
2020-11-17 11:02:43.704 [main] INFO  o.s.scheduling.concurrent.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'

或者可以通过引入ApplicationEventPublisher,在我们的方法内部发布一个监听事件。

@RestController
public class XiaoAMaController  {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

	@GetMapping(value = "/createUser")
    public User create() {
        User user = new CacheUser(); 
        user.setName("xiaoama");
        user.setId(1);
        user.setAddress("cd");
        applicationEventPublisher.publishEvent(new XiaoAMaCreatedEvent(user,"create account success"));
        return user;
    }
}

通过postman调用createUser接口,也可以看到同样的打印信息,表明我们的监听器已经成功的注册到spring的上下文容器中。

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐