问题描述
我想开发一个Spring AOP功能,我们可以在spring bean初始化期间放置一个切入点/切入点,以便根据业务需要计算一些统计信息.我想知道是否可以使用spring AOP模块?
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?
推荐答案
您可以使用以下组件来测量初始化时间:
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.
但是您可以在读取所有bean定义之后记录一下,然后运行所有bean构造函数.为此使用BeanFactoryPostProccessor:
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;
}
}
lauchTime是弹簧刚完成读取配置(例如xml文件)并准备创建bean的时刻.
The lauchTime is a moment when the spring just finished reading the configuration (for example, xml file) and ready to create beans.
因此,可以使用这两个组件来计算完整的初始化时间,例如:max(end)-launchTime. (最后一个bean的初始化时间与读取bean的配置之间的差异)
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)
这篇关于我们可以计算Spring bean的初始化时间吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!