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

只需要实现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()方法 即可

posted @ 2018-03-08 12:02  精灵壶  阅读(2937)  评论(7编辑  收藏  举报