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 bus
You can measure initialization time using this component:
@Component
public class MyBeanPostProcessor implements BeanPostProcessor, Ordered {
private Map start;
private Map 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)