springboot 显示打印加载bean耗时工具类的案例
目录
- 一 spring的原生接口说明
- 1.1 接口说明
- 1.2 案例说明
一 spring的原生接口说明
1.1 接口说明
Aware是Spring框架提供的一组特殊接口,可以让Bean从Spring容器中拿到一些资源信息。
BeanFactoryAware:实现该接口,可以访问BeanFactory对象,从而获取Bean在容器中的相关信息。
EnvironmentAware:实现该接口,可以访问Environment对象,从而获取环境相关的配置属性,比如系统属性、环境变量等。
ResourceLoaderAware:实现该接口,可以访问ResourceLoader对象,从而获取资源加载器,用于加载类路径下的资源文件。
MessageSourceAware:实现该接口,可以访问MessageSource对象,从而获取国际化消息。
1.2 案例说明
1.打印耗时
package com.ljf.springboot.mybaits.demos.config; /** * @ClassName: TimeCostBeanPostProcessor python * @Descripythonption: TODO * @Author: admin * @Date: 2025/06/29 17:48:32 * @Version: V1.0 **/ import com.google.common.collect.Maps; import org.springframework.beans.BeansException; import org.springframewhttp://www.devze.comork.beans.factory.config.BeanPostProcessor; import org.springframework.stereotype.Component; import Java.util.Map; /** * @author admin * @description 这个类实现了Spring框架的BeanPostProcessor接口,用于在bean初始化前后记录每个bean的创建时间成本 * @param * @return */ @Component public class TimeCostBeanPostProcessor implements BeanPostProcessor { private Map<String, Long> costMap = Maps.newConcurrentMap(); private Long costSumTime = 0L; @Override publjavascriptic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { costMap.put(beanName, System.currentTimeMillis()); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (costMap.containsKey(beanName)) { Long start = costMap.get(beanName); long cost = System.currentTimeMillis() - start; if (cost > 0) { costMap.put(beanName, cost); System.out.println("bean: " + beanName + "\ttime: " + cost); } } return bean; } }
2.监控事件
package com.ljf.springboot.mybaits.demos.config; /** * @ClassName: ApplicationEventListener * @Description: TODO * @Author: admin * @Date: 2025/06/29 17:44:41 * @Version: V1.0 **/ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; /** * @author admin * @description 这个类实现了Spring框架的ApplicationListener<ApplicationEvent>接口,用于监听并处理应用上下文中的事件。 * @param * @return */ @Component public class ApplicationEventListener implements ApplicationListener<ApplicationEvent> { private static final Logger logger = LoggerFactory.getLogger(ApplicationEventListener.class); @Ovewww.devze.comrride public void onApplicationEvent(ApplicationEvent event) { logger.info("=======event received : {}", event.getClass().getName()); } }
测试案例结果:
到此这篇关于springboot 显示打印加载bean耗时工具类的文章就介绍到这了,更多相关springboot 打印加载bean内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论