Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we calculate Spring bean initialization time

I would like to develop a spring AOP feature where we can put a point cut/within during the spring bean initialization so as to calculate some statistics as required for business. I would like to know if its possible using spring AOP module?

like image 909
Vikas Chowdhury Avatar asked Mar 12 '23 13:03

Vikas Chowdhury


1 Answers

You can measure initialization time using this component:

@Component
public class MyBeanPostProcessor implements BeanPostProcessor, Ordered {

    private Map<String, Long> start;

    private Map<String, Long> end;

    public MyBeanPostProcessor() {
        start = new HashMap<>();
        end = new HashMap<>();
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        start.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        end.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public int getOrder() {
        return Integer.MAX_VALUE;
    }

    //this method returns initialization time of the bean.
    public long initializationTime(String beanName) {
       return end.get(beanName) - start.get(beanName);
    }
}

But this time doesn't include time of running constructor.

But you can chronicle a moment after reading bean definition before all bean constructors are run. Use BeanFactoryPostProccessor for it:

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {

    private long launchTime;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        launchTime = System.currentTimeMillis();
    }

    public long getLaunchTime() {
        return launchTime;
    }
}

The lauchTime is a moment when the spring just finished reading the configuration (for example, xml file) and ready to create beans.

So, the full initialization time can be calculated use this two components like: max(end) - launchTime. (The difference between the time last bean was initialized and bean configuration was read)

like image 77
kosbr Avatar answered Mar 20 '23 11:03

kosbr