只需要實現spring自帶的一個接口 InitializingBean 並把方法注冊到spring容器中即可
package jpj.boot.listener; import com.alibaba.fastjson.JSON; import jpj.boot.service.UserService; import lombok.extern.log4j.Log4j2; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeansException; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import javax.annotation.Resource; /** * @Author: jingpj * @Date:creste in 2018/3/8 */ @Component @Log4j2 public class InitListener implements InitializingBean, ApplicationContextAware { @Resource private UserService userService; @Override public void afterPropertiesSet() throws Exception { //applicationContext.getBean() log.info("initstart------------------------++++++++++++++++++++++"); log.info(userService.getClass().toString()); log.info(JSON.toJSONString(userService.selectByPrimaryKey(1))); } private ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
與之對應的還有容器關閉前的 DisposableBean
package org.springframework.beans.factory; public interface DisposableBean { void destroy() throws Exception; }
實現接口 重寫 destroy()方法 即可