mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-08-18 20:38:02 +08:00
Add: SpringUtil.getBean(TypeReference<T>)
添加Spring工具类静态方法,通过类型参考(TypeReference)获取带泛型参数的Bean,同时添加了一个小的单元测试
This commit is contained in:
@@ -1,10 +1,16 @@
|
||||
package cn.hutool.extra.spring;
|
||||
|
||||
import cn.hutool.core.lang.ParameterizedTypeImpl;
|
||||
import cn.hutool.core.lang.TypeReference;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.core.ResolvableType;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -73,6 +79,22 @@ public class SpringUtil implements ApplicationContextAware {
|
||||
return applicationContext.getBean(name, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过类型参考返回带泛型参数的Bean
|
||||
*
|
||||
* @param reference 类型参考,用于持有转换后的泛型类型
|
||||
* @param <T> Bean类型
|
||||
* @return 带泛型参数的Bean
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> T getBean(TypeReference<T> reference) {
|
||||
ParameterizedType parameterizedType = (ParameterizedType) reference.getType();
|
||||
Class<T> rawType = (Class<T>) parameterizedType.getRawType();
|
||||
Class<?>[] genericTypes = Arrays.stream(parameterizedType.getActualTypeArguments()).map(type -> (Class<?>) type).toArray(Class[]::new);
|
||||
String[] beanNames = applicationContext.getBeanNamesForType(ResolvableType.forClassWithGenerics(rawType, genericTypes));
|
||||
return applicationContext.getBean(beanNames[0], rawType);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定类型对应的所有Bean,包括子类
|
||||
*
|
||||
|
Reference in New Issue
Block a user