您的位置:首页 > 编程语言 > Java开发

spring在bean加载完成后初始化代码

2018-03-08 12:02 417 查看
只需要实现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()方法 即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: