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()方法 即可


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2024 CODEPRJ.COM