业务代码测试工具类utils

import org.springframework.beans.BeansException;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @create 2020-08-05
 * @description
 */
public class Test {

    /**
     * 启动来源类
     */
    static Class[] SOURCES = {ApiContext.class};

    /**
     * 测试代码
     */
    public void test() {
        DefinitionCache definitionCache = getBean("definitionCache", DefinitionCache.class);
        System.out.println(definitionCache);
        System.out.println(definitionCache.getAllLabelInfo());
        System.out.println(springInvokeMethod("definitionCache", "getAllLabelInfo", null));
    }

    /**
     * 获取bean
     *
     * @param name service注解方式name为小驼峰格式
     * @return Object bean的实例对象
     */
    private static  T getBean(String name, Class requiredType) throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    /**
     * 执行bean中方法
     *
     * @param serviceName
     * @param methodName
     * @param params
     * @return
     */
    private static Object springInvokeMethod(String serviceName, String methodName, Object... params) {
        Object service = applicationContext.getBean(serviceName);
        Class[] paramClass = null;
        if (Objects.nonNull(params)) {
            int paramsLength = params.length;
            paramClass = new Class[paramsLength];
            for (int i = 0; i < paramsLength; i++) {
                paramClass[i] = params[i].getClass();
            }
        }
        // 找到方法
        Method method = ReflectionUtils.findMethod(service.getClass(), methodName, paramClass);
        // 执行方法
        return ReflectionUtils.invokeMethod(method, service, params);
    }


    private static ApplicationContext applicationContext;

    /**
     * 启动
     */
    public static void main(String[] args) {
        // 启动Spring应用
        SpringApplication springApplication = new SpringApplication(SOURCES);
        applicationContext = springApplication.run();

        new Test().test();
    }

}

你可能感兴趣的:(utils)