springboot 显示打印加载bean耗时工具类

发布于:2025-07-03 ⋅ 阅读:(20) ⋅ 点赞:(0)

一  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
 * @Description: 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.springframework.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
    public 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);

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        logger.info("=======event received : {}", event.getClass().getName());
    }
}

测试案例结果:

 

 


网站公告

今日签到

点亮在社区的每一天
去签到