java - Can we calculate Spring bean intialization time -


i develop spring aop feature can put point cut/within during spring bean intialization calculate statistics required business. know if possible using spring aop module?

you can measure initialization time using 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 bean.     public long initializationtime(string beanname) {        return end.get(beanname) - start.get(beanname);     } } 

but time doesn't include time of running constructor.

but can chronicle moment after reading bean definition before bean constructors run. use beanfactorypostproccessor 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 moment when spring finished reading configuration (for example, xml file) , ready create beans.

so, full initialization time can calculated use 2 components like: max(end) - launchtime. (the difference between time last bean initialized , bean configuration read)


Comments