一 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());
}
}测试案例结果:

到此这篇关于springboot 显示打印加载bean耗时工具类的文章就介绍到这了,更多相关springboot 打印加载bean内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论