Spring
通过ApplicationContextAware
反射调用服Bean方法,ApplicationContextAware
常用方法封装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| @Configuration public class SpringReflectUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringReflectUtils.applicationContext = applicationContext; }
public static boolean containsBean(String name) { return applicationContext.containsBean(name); }
public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); }
public static <T> T getBean(Class<T> requiredType) throws BeansException { return applicationContext.getBean(requiredType); }
public static <T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException { return applicationContext.getBeansOfType(type); }
public static Object springInvokeMethod(String serviceName, String methodName, Object[] params) throws Exception { Object service = getBean(serviceName); Class<? extends Object>[] paramClass = null; if (params != null) { 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); } }
|