处理spring动态注入:
package com.xxl.job.executor.mvc.controller;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtils implements ApplicationContextAware {
static ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
SpringContextUtils.context = context;
}
public static ApplicationContext getContext() {
return context;
}
public static void autowireBean(Object bean) {
context.getAutowireCapableBeanFactory().autowireBean(bean);
}
public static <T> T getBean(Class<T> clazz) {
return context.getBean(clazz);
}
}
示例参考:
package com.xxl.job.executor.mvc.controller;
import com.xxl.job.core.handler.IJobHandler;
import groovy.lang.GroovyClassLoader;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@EnableAutoConfiguration
public class IndexController {
@RequestMapping("/")
@ResponseBody
public String index() {
return "xxl job executor running.";
}
@RequestMapping("/index2")
public void index2() throws Exception {
GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
String codeSource = "package com.xxl.job.service.handler; " +
" " +
"import com.xxl.job.core.context.XxlJobHelper; " +
"import com.xxl.job.core.handler.IJobHandler; " +
"import com.xxl.job.executor.mvc.controller.IndexController; " +
"import org.slf4j.Logger; " +
"import org.slf4j.LoggerFactory; " +
"import org.springframework.beans.factory.annotation.Autowired; " +
" " +
"public class DemoGlueJobHandler2 extends IJobHandler { " +
" private static Logger logger = LoggerFactory.getLogger(DemoGlueJobHandler2.class); " +
" " +
" @Autowired " +
" private IndexController c2; " +
" " +
" @Override " +
" public void execute() throws Exception{ " +
" logger.info(\"------------------actJobHandler2 job start----------------\"); " +
" logger.info(\"测试glue模式 XxlJobHelper2.log\"+c2.index()); " +
" logger.info(\"------------------actJobHandler2 job end----------------\"); " +
" } " +
" " +
"} ";
Class<?> clazz = groovyClassLoader.parseClass(codeSource);
if (clazz != null) {
Object instance = clazz.newInstance();
SpringContextUtils.autowireBean(instance); // 对脚本java中的Autowired成员变量进行注入
if (instance!=null) {
if (instance instanceof IJobHandler) {
IJobHandler instance1 = (IJobHandler) instance;
instance1.execute();
}
}
}
}
}