SpringBoot 的自定义Listener

目录

1、自定义监听的用途 

2、在SpringBoot之中实现加载自定义监听的方法

2.1、基于servlet的ServletContextListener

2.2、使用基于spring的 ApplicationListener

3、展示写入的Redis的效果如下图所示:


1、自定义监听的用途 

因为有些系统项目的需要,需要在系统启动的过程之中,直接刷入缓存,或者初始化一些常用系统参数,此时可以使用Listener来实现。比如在系统启动的过程之中刷入数据字典到缓存Redis之中,以及系统常用参数变量到缓存Redis之中。

如下图所示:

 

2、在SpringBoot之中实现加载自定义监听的方法

主要有两种实现方式:

2.1、基于servlet的ServletContextListener

此种方式需要注意:需要在启动类加上@ServletComponentScan注解

/***
 *@purpose:刷新缓存数据的监听
 *@author:jianxiapc
 *@since:2018年7月17日
 ***/
@WebListener
public class CacheServletListener implements ServletContextListener {
	
	@Autowired
	private RedisStringService redisStringService;
	
	@Autowired
	private RedisKeyOperateService redisKeyOperateService;
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("CacheListener contextDestroyed method");
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		//initCache(arg0);
		redisStringService.set("systemNameServletWrite", "whdcmap-web");
		System.out.println("initCache completed!");
	}
}

2.2、使用基于spring的 ApplicationListener

@Service
public class CacheSpringListener implements ApplicationListener<ApplicationEvent> {
	
	@Autowired
	private RedisStringService redisStringService;
	
	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		redisStringService.set("systemNameSpringWrite", "whdcmap-web");
		System.out.println("initCache completed!");
	}
	
}

3、展示写入的Redis的效果如下图所示:

参考文章:springboot的自定义Listener

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot提供了一种自定义事件的机制,可以在应用程序中定义自己的事件,并在需要的时候发布这些事件。自定义事件可以用于在应用程序中实现解耦,使得不同的组件之间可以松散地耦合在一起。下面是一个简单的示例,演示如何在Spring Boot应用程序中定义和发布自定义事件: 1.定义一个自定义事件类,继承自ApplicationEvent类,例如MyEvent: ```java public class MyEvent extends ApplicationEvent { private String message; public MyEvent(Object source, String message) { super(source); this.message = message; } public String getMessage() { return message; } } ``` 2.定义一个事件发布者类,例如MyEventPublisher: ```java @Component public class MyEventPublisher { @Autowired private ApplicationEventPublisher publisher; public void publishEvent(String message) { publisher.publishEvent(new MyEvent(this, message)); } } ``` 3.定义一个事件监听器类,例如MyEventListener: ```java @Component public class MyEventListener { @EventListener public void onApplicationEvent(MyEvent event) { System.out.println("Received spring custom event - " + event.getMessage()); } } ``` 4.在需要发布事件的地方,注入MyEventPublisher并调用publishEvent方法即可: ```java @Autowired private MyEventPublisher publisher; ... publisher.publishEvent("Hello, world!"); ``` 这样,当应用程序发布MyEvent事件时,MyEventListener中的onApplicationEvent方法将被调用,并输出事件的消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值