Java SpringBoot 中,动态执行 bean 对象中的方法

打印 上一主题 下一主题

主题 889|帖子 889|积分 2671

根据不同的条件,调用不同的 bean 对象,执行对象中的方法
SpringUtils 工具类
  1. package com.vipsoft.web.utils;
  2. import cn.hutool.core.util.ArrayUtil;
  3. import org.springframework.aop.framework.AopContext;
  4. import org.springframework.beans.BeansException;
  5. import org.springframework.beans.factory.NoSuchBeanDefinitionException;
  6. import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
  7. import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.ApplicationContextAware;
  10. import org.springframework.stereotype.Component;
  11. /**
  12. * Spring工具类 方便在非 Spring 管理环境中获取bean
  13. *
  14. */
  15. @Component
  16. public final class SpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware {
  17.     /**
  18.      * Spring 应用上下文环境
  19.      */
  20.     private static ConfigurableListableBeanFactory beanFactory;
  21.     private static ApplicationContext applicationContext;
  22.     @Override
  23.     public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
  24.         SpringUtils.beanFactory = beanFactory;
  25.     }
  26.     @Override
  27.     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  28.         SpringUtils.applicationContext = applicationContext;
  29.     }
  30.     /**
  31.      * 获取对象
  32.      *
  33.      * @param name
  34.      * @return Object 一个以所给名字注册的bean的实例
  35.      * @throws BeansException
  36.      */
  37.     @SuppressWarnings("unchecked")
  38.     public static <T> T getBean(String name) throws BeansException {
  39.         return (T) beanFactory.getBean(name);
  40.     }
  41.     /**
  42.      * 获取类型为requiredType的对象
  43.      *
  44.      * @param clz
  45.      * @return
  46.      * @throws BeansException
  47.      */
  48.     public static <T> T getBean(Class<T> clz) throws BeansException {
  49.         T result = (T) beanFactory.getBean(clz);
  50.         return result;
  51.     }
  52.     /**
  53.      * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
  54.      *
  55.      * @param name
  56.      * @return boolean
  57.      */
  58.     public static boolean containsBean(String name) {
  59.         return beanFactory.containsBean(name);
  60.     }
  61.     /**
  62.      * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
  63.      *
  64.      * @param name
  65.      * @return boolean
  66.      * @throws NoSuchBeanDefinitionException
  67.      */
  68.     public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
  69.         return beanFactory.isSingleton(name);
  70.     }
  71.     /**
  72.      * @param name
  73.      * @return Class 注册对象的类型
  74.      * @throws NoSuchBeanDefinitionException
  75.      */
  76.     public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
  77.         return beanFactory.getType(name);
  78.     }
  79.     /**
  80.      * 如果给定的bean名字在bean定义中有别名,则返回这些别名
  81.      *
  82.      * @param name
  83.      * @return
  84.      * @throws NoSuchBeanDefinitionException
  85.      */
  86.     public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
  87.         return beanFactory.getAliases(name);
  88.     }
  89.     /**
  90.      * 获取aop代理对象
  91.      *
  92.      * @param invoker
  93.      * @return
  94.      */
  95.     @SuppressWarnings("unchecked")
  96.     public static <T> T getAopProxy(T invoker) {
  97.         return (T) AopContext.currentProxy();
  98.     }
  99.     /**
  100.      * 获取当前的环境配置,无配置返回null
  101.      *
  102.      * @return 当前的环境配置
  103.      */
  104.     public static String[] getActiveProfiles() {
  105.         return applicationContext.getEnvironment().getActiveProfiles();
  106.     }
  107.     /**
  108.      * 获取当前的环境配置,当有多个环境配置时,只获取第一个
  109.      *
  110.      * @return 当前的环境配置
  111.      */
  112.     public static String getActiveProfile() {
  113.         final String[] activeProfiles = getActiveProfiles();
  114.         return ArrayUtil.isNotEmpty(activeProfiles) ? activeProfiles[0] : null;
  115.     }
  116. }
复制代码
执行类
  1. package com.vipsoft.web.task;
  2. import cn.hutool.core.date.DateUtil;
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.stereotype.Component;
  6. @Component("scheduletask")
  7. public class ScheduleTask {
  8.     protected final Logger logger = LoggerFactory.getLogger(this.getClass());
  9.     public void execute(String param) {
  10.         logger.info("执行 Schedule Task,当前时间:{},任务参数:{}", DateUtil.now(), param);
  11.     }
  12. }
复制代码
测试类
  1. package com.vipsoft.web;
  2. import cn.hutool.core.util.StrUtil;
  3. import com.vipsoft.web.utils.SpringUtils;
  4. import org.junit.jupiter.api.Test;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import java.lang.reflect.Method;
  7. @SpringBootTest
  8. public class SpringUtilTest {
  9.     @Test
  10.     void invokeTest() throws Exception {
  11.         //点前面的做为 bean 名称,后面是方法名,(中是参数==参数可以放JSON)
  12.         String invokeTarget = "scheduletask.execute('VipSoft Quartz')";
  13.         invokeMethod(invokeTarget);
  14.     }
  15.     void invokeMethod(String invokeTarget) throws Exception {
  16.         String beanName = StrUtil.subBefore(invokeTarget, ".", true);
  17.         String methodName = StrUtil.subBetween(invokeTarget, ".", "(");
  18.         String param = StrUtil.subBetween(invokeTarget, "(", ")");
  19.         Object bean;
  20.         if (StrUtil.count(beanName, ".") == 0) {
  21.             bean = SpringUtils.getBean(beanName);
  22.         } else {
  23.             //Package 的形式得到 Bean,如: beanName="com.vipsoft.web.task.ScheduleTask"
  24.             bean = Class.forName(beanName).newInstance();
  25.         }
  26.         if (bean != null) {
  27.             if (StrUtil.isNotEmpty(param)) {
  28.                 Method method = bean.getClass().getDeclaredMethod(methodName, String.class);
  29.                 method.invoke(bean, param);
  30.             } else {
  31.                 Method method = bean.getClass().getDeclaredMethod(methodName);
  32.                 method.invoke(bean);
  33.             }
  34.         }
  35.     }
  36. }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

刘俊凯

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表