@EventListener 是spring对事件监听的注解,在类上实现下面的代码,并重写方法也是可以实现事件监听的。
implements ApplicationListener
@EventListener 后续是可以添加参数的,比如:
@EventListener(ApplicationReadyEvent.class)
这个意思是待spring上下文启动完毕后,加载注解所在的方法。这个注解就是监听器。
目前已知的几种监听类型:
-
ApplicationFailedEvent:该事件为spring boot启动失败时触发
-
ApplicationPreparedEvent:上下文context准备时触发
-
ApplicationReadyEvent:上下文已经准备完毕的时候触发
-
ApplicationStartedEvent:spring boot 启动监听类
-
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