Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log spring Bean instantiation

Tags:

java

spring

How can we log each bean instantiation in Spring?

  • I wish to log a message every time a bean is initialized.
  • I have N number of bean and I don't want to put any logger on init method for each bean.
  • I see this as a cross-cutting concern, but not sure how to achieve this.

Is there a way.?

like image 588
Sanjay Singh Avatar asked Sep 01 '17 08:09

Sanjay Singh


1 Answers

You can use a BeanPostProcessor

@Component
public class LogBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName)
        throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {
        LOGGER.log(String.format("Bean instantiated with name %s and class %s", beanName, bean.getClass().getSimpleName()));
        return bean;
    }
}
like image 191
yaswanth Avatar answered Nov 15 '22 03:11

yaswanth