一? 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;@Overridepublic Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {costMap.put(beanName, System.currentTimeMillis());return bean;}@Overridepublic 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);@Overridepublic void onApplicationEvent(ApplicationEvent event) {logger.info("=======event received : {}", event.getClass().getName());}
}
測試案例結果:
?
?