概述
遇到一个需求: 需要执行 bean
中不固定的方法.
当前第一想法是像 MQ
配置文件一样, 动态配置 bean
和 method
.
最终确定用反射来实现.
目的
实现
反射实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @Service @Slf4j public class ChatRouter { public SocketResult goRoute(String currentUserId, String message) { String beanName = "testBean"; String methodName = "testMethod"; Object bean = SpringBeanUtil.getApplicationContext().getBean(beanName); try { Class<?> c = bean.getClass(); Method m = c.getMethod(methodName, String.class, String.class); Object result = m.invoke(bean, currentUserId, message); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } }
|
TestBean
1 2 3 4 5 6 7 8
| @Service("testBean") public class TestBean { public String testMethod(String currentUserId, String message) { return "调用成功"; } }
|
SpringBeanUtil
动态获取 bean
当前工具类用于根据 bean name
获取 bean
对象使用.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Component public class SpringBeanUtil implements ApplicationContextAware { private static ApplicationContext applicationContext;
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringBeanUtil.applicationContext = applicationContext; }
public static ApplicationContext getApplicationContext() { return applicationContext; } }
|
本文地址: https://github.com/maxzhao-it/blog/post/2700/