根据不同的条件,调用不同的 bean 对象,执行对象中的方法
SpringUtils 工具类执行类- package com.vipsoft.web.task;
- import cn.hutool.core.date.DateUtil;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.stereotype.Component;
- @Component("scheduletask")
- public class ScheduleTask {
- protected final Logger logger = LoggerFactory.getLogger(this.getClass());
- public void execute(String param) {
- logger.info("执行 Schedule Task,当前时间:{},任务参数:{}", DateUtil.now(), param);
- }
- }
复制代码 测试类- package com.vipsoft.web;
- import cn.hutool.core.util.StrUtil;
- import com.vipsoft.web.utils.SpringUtils;
- import org.junit.jupiter.api.Test;
- import org.springframework.boot.test.context.SpringBootTest;
- import java.lang.reflect.Method;
- @SpringBootTest
- public class SpringUtilTest {
- @Test
- void invokeTest() throws Exception {
- //点前面的做为 bean 名称,后面是方法名,(中是参数==参数可以放JSON)
- String invokeTarget = "scheduletask.execute('VipSoft Quartz')";
- invokeMethod(invokeTarget);
- }
- void invokeMethod(String invokeTarget) throws Exception {
- String beanName = StrUtil.subBefore(invokeTarget, ".", true);
- String methodName = StrUtil.subBetween(invokeTarget, ".", "(");
- String param = StrUtil.subBetween(invokeTarget, "(", ")");
- Object bean;
- if (StrUtil.count(beanName, ".") == 0) {
- bean = SpringUtils.getBean(beanName);
- } else {
- //Package 的形式得到 Bean,如: beanName="com.vipsoft.web.task.ScheduleTask"
- bean = Class.forName(beanName).newInstance();
- }
- if (bean != null) {
- if (StrUtil.isNotEmpty(param)) {
- Method method = bean.getClass().getDeclaredMethod(methodName, String.class);
- method.invoke(bean, param);
- } else {
- Method method = bean.getClass().getDeclaredMethod(methodName);
- method.invoke(bean);
- }
- }
- }
- }
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |