工具类 SpringUtil 实现 bean 获取
底层源码
@Component
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContextParam) throws BeansException {
applicationContext=applicationContextParam;
}
public static Object getObject(String id) {
Object object = null;
object = applicationContext.getBean(id);
return object;
}
public static <T> T getObject(Class<T> tClass) {
return applicationContext.getBean(tClass);
}
public static Object getBean(String tClass) {
return applicationContext.getBean(tClass);
}
public static <T> T getBean(String str,Class<T> tClass) {
return (T)applicationContext.getBean(str);
}
public <T> T getBean(Class<T> tClass) {
return applicationContext.getBean(tClass);
}
}
实际应用
IDynamicSqlService dynamicSqlService = SpringUtil.getBean(IDynamicSqlService.class);
实际应用的SpringUtil.getBean(IDynamicSqlService.class)也是基于刀锋框架的二次封装方法来实现应用的。
解析
由于类名获取更快,字符串hash计算没类直接获取hash快,所以getBean(Class tClass)更好,更建议使用。
刀锋框架二次封装
图片:

SpringUtil获取bean的实战与源码解析
本文探讨了如何使用SpringUtil工具类来获取bean,重点在于其底层源码的分析,以及在实际应用中如何利用刀锋框架进行二次封装。建议使用getBean(Class tClass)方法,因为类名获取速度更快。
5102

被折叠的 条评论
为什么被折叠?



