参考博客
@Slf4j
@Api(tags = "Spring Controller")
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/hello/spring")
public class SpringController {
@Autowired
private SpringService springService;
@ApiOperation("获取BeanName")
@GetMapping("getBeanNames")
public WebResult<List<String>> getBeanNames() {
List<String> beanNameList = springService.getBeanNames();
return WebResult.success(beanNameList);
}
@ApiOperation("获取Bean方法")
@GetMapping("getBeanMethods")
public WebResult<List<String>> getBeanMethods(@RequestParam String beanName) {
List<String> beanMethodList = springService.getBeanMethods(beanName);
return WebResult.success(beanMethodList);
}
@ApiOperation("执行Bean方法")
@PostMapping("invokeBeanMethod")
public WebResult<List<String>> methodDemo(@RequestBody SpringBeanInfo springBeanInfo) {
Object result = springService.invokeBeanMethod(springBeanInfo);
return WebResult.success(result);
}
}
@Slf4j
@Service
public class SpringServiceImpl implements SpringService {
@Override
public List<String> getBeanNames() {
ApplicationContext applicationContext = SpringBeanUtils.getApplicationContext();
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
List<String> beanNameList = Arrays.stream(beanDefinitionNames)
.filter(beanDefinitionName -> !beanDefinitionName.startsWith("org.") && !beanDefinitionName.startsWith("spring."))
.collect(Collectors.toList());
log.info("getBeanNames beanNameList: {}", JSON.toJSONString(beanNameList));
return beanNameList;
}
@Override
public List<String> getBeanMethods(String beanName) {
List<String> methodList = new ArrayList<>();
Object beanObj = SpringBeanUtils.getBean(beanName);
Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(beanObj.getClass());
for (Method method : methods) {
StringBuilder sb = new StringBuilder(method.getName());
Type[] genericParameterTypes = method.getGenericParameterTypes();
sb.append("(");
for (Type type : genericParameterTypes) {
sb.append(type.getTypeName()).append(",");
}
if (genericParameterTypes.length > 0) {
sb.deleteCharAt(sb.length() - 1);
}
sb.append(")");
methodList.add(sb.toString());
}
log.info("getBeanMethods methodList: {}", JSON.toJSONString(methodList));
return methodList;
}
@Override
public Object invokeBeanMethod(SpringBeanInfo springBeanInfo) {
try {
Object proxyObj = SpringBeanUtils.getBean(springBeanInfo.getBeanName());
Method proxyMethod = SpringBeanUtils.getMethod(proxyObj.getClass(), springBeanInfo.getMethodName());
if (proxyMethod == null) {
return null;
}
List<Object> parameterList = SpringBeanUtils.getMethodParamList(proxyMethod, springBeanInfo.getParamMap());
Object result = proxyMethod.invoke(proxyObj, parameterList.toArray());
log.info("invokeBeanMethod result: {}", JSON.toJSONString(result));
return result;
} catch (Exception e) {
log.error("invokeBeanMethod catch exception springBeanInfo: {}", JSON.toJSONString(springBeanInfo), e);
}
return null;
}
/**
* 执行方法
*
* @param springBeanInfo springBean信息
* @return 执行结果
*/
private Object invokeMethod(SpringBeanInfo springBeanInfo) {
Object beanObj = SpringBeanUtils.getBean(springBeanInfo.getBeanName());
Method method = ReflectionUtils.findMethod(beanObj.getClass(), springBeanInfo.getMethodName());
Object result = ReflectionUtils.invokeMethod(method, beanObj, springBeanInfo.getParamMap());
return result.toString();
}
}
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
@Component
public class SpringBeanUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
private static final List<Class> PRIMARY_CLASS = Arrays.asList(Integer.class, Boolean.class,
Double.class, Byte.class, Short.class, Long.class, Float.class, BigDecimal.class, String.class);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringBeanUtils.applicationContext = applicationContext;
}
/**
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* 获取指定Bean
*
* @param clazz clazz
* @param <T> 泛型
* @return 结果
*/
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
/**
* 根据Bean名称获取Bean
*
* @param beanName Bean名称
* @param <T> Bean名称
* @return Bean对象
*/
public static <T> Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
/**
* 根据方法名获取指定方法
*
* @param proxyObject 类
* @param methodName 方法名
* @return 指定方法
*/
public static Method getMethod(Class<?> proxyObject, String methodName) {
Method[] methods = proxyObject.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
return method;
}
}
return null;
}
/**
* 获取方法实际参数
*
* @param method 方法
* @param paramMap 参数
* @return 实际参数
* @throws Exception 异常
*/
public static List<Object> getMethodParamList(Method method, Map<String, String> paramMap) throws Exception {
List<Object> objects = new ArrayList<>();
for (Class<?> parameterType : method.getParameterTypes()) {
Object obj = null;
if (PRIMARY_CLASS.contains(parameterType)) {
obj = paramMap.get(parameterType.getTypeName());
} else if (!parameterType.isPrimitive()) {
obj = getInstance(parameterType);
// 将 map 拷贝到 bean 中
String value = paramMap.get(parameterType.getTypeName());
BeanUtils.populate(obj, JSON.parseObject(value));
}
objects.add(obj);
}
return objects;
}
/**
* 获取类型实例
*
* @param parameterType 参数类型
* @return 结果
*/
private static Object getInstance(Class<?> parameterType) throws Exception {
if (parameterType.isAssignableFrom(List.class)) {
return new ArrayList<>();
} else if (parameterType.isAssignableFrom(Map.class)) {
return new HashMap<>();
} else if (parameterType.isAssignableFrom(Set.class)) {
return new HashSet<>();
}
return parameterType.newInstance();
}
}