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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…