@EventListener和@PostConstruct的使用

@EventListener 是spring对事件监听的注解,在类上实现下面的代码,并重写方法也是可以实现事件监听的。

implements ApplicationListener

@EventListener 后续是可以添加参数的,比如:

@EventListener(ApplicationReadyEvent.class)

这个意思是待spring上下文启动完毕后,加载注解所在的方法。这个注解就是监听器。

目前已知的几种监听类型:

  1. ApplicationFailedEvent:该事件为spring boot启动失败时触发

  2. ApplicationPreparedEvent:上下文context准备时触发

  3. ApplicationReadyEvent:上下文已经准备完毕的时候触发

  4. ApplicationStartedEvent:spring boot 启动监听类

  5. SpringApplicationEvent:获取SpringApplication

ApplicationEnvironmentPreparedEvent:环境事先准备
---------------------------------------------------------------------------------------------------------------------------------
@PostConstruct 注解的使用,它会在服务器加载servlet是运行,仅一次
说白了就是初始化的时候执行,相当于init();

这个注解是不能有参数的。

如果你想让程序中的某个方法在程序启动后执行,最好用@EventListener,如果用@PostConstruct,首先,会很被动,因为这个注解是自动识别,执行方法的,如果你方法中的某些bean还未被注入的话,是会报空指针异常的。

Caused by: java.lang.NullPointerException: null
	at xxx.xxx.xxx.common.ApplicationContextProvider.getBean(ApplicationContextProvider.java:25)
	at xxx.xxx.xxx.http.RequestUtil.get(RequestUtil.java:119)
	at xxx.xxx.xxx.http.RequestUtil.get(RequestUtil.java:42)
	at xxx.xxx.xxx.http.RequestUtil.requestByGet(RequestUtil.java:131)
	at xxx.xxx.xxx.core.service.PricePoolService.init(PricePoolService.java:46)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:369)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:312)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:135)
	... 66 common frames omitted

我感觉还是因为方法中需要的内容还未被注入。换成下面的就好了。

@EventListener(ApplicationReadyEvent.class)
爱学习,爱java
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值