Sunday, June 16, 2019

Spring bean lifecycles and BeanPostProcessor


import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class MyComponent implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet from InitializingBean");
}

@PostConstruct
public void onPostConstruct() {
System.out.println("onPostConstruct");
}

@PreDestroy
public void onPreDestroy() {
System.out.println("onPreDestroy");
}


@Override
public void destroy() throws Exception {
System.out.println("destroy from DisposableBean ");
}


}

the sequence is:

onPostConstruct
afterPropertiesSet from InitializingBean
onPreDestroy
destroy from DisposableBean



and you can intercept instantiatio of every bean with a BPP :


import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomBeanPostProcessor implements BeanPostProcessor {

    public CustomBeanPostProcessor() {
        System.out.println("0. Spring calls constructor");
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {
        System.out.println(bean.getClass() + "  " + beanName);
        return bean;
    }
}



No comments: