Auto‑Registration of Executors and JobHandlers for XXL‑Job with a Spring Boot Starter
The Spring Boot starter automatically registers XXL‑Job executors and job handlers at application startup by logging into the admin console, scanning beans for methods annotated with @XxlJob and @XxlRegister, and invoking the admin APIs to create missing groups and jobs, eliminating manual configuration.
XXL‑Job is a lightweight, distributed task‑scheduling middleware. When a project contains dozens or hundreds of scheduled jobs, manually registering each executor and job in the XXL‑Job admin console becomes tedious.
Analysis
The goal is to eliminate manual registration by automatically creating executors and job handlers during application startup.
Core Steps
Identify the required admin APIs: /jobgroup/save , /jobgroup/pageList , /jobinfo/add , /jobinfo/pageList .
Handle authentication by logging in to the admin console and storing the XXL_JOB_LOGIN_IDENTITY cookie.
Implement a Spring ApplicationListener<ApplicationReadyEvent> that triggers the auto‑registration logic after the context is ready.
Interface Calls
Login service obtains the cookie:
private final Map
loginCookie = new HashMap<>();
public void login(){
String url = adminAddresses + "/login";
HttpResponse response = HttpRequest.post(url)
.form("userName", username)
.form("password", password)
.execute();
// extract XXL_JOB_LOGIN_IDENTITY cookie
}Subsequent API calls reuse the cookie and retry up to three times if it expires.
Annotation Design
A custom annotation @XxlRegister is introduced to supply job metadata (cron, description, author, trigger status). It works together with the native @XxlJob annotation.
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface XxlRegister {
String cron();
String jobDesc() default "default jobDesc";
String author() default "default Author";
int triggerStatus() default 0;
}Auto‑Register Core
The listener scans the Spring context for beans containing methods annotated with both @XxlJob and @XxlRegister . For each method it:
Checks whether the executor (identified by appName and title ) already exists via /jobgroup/pageList .
If missing, registers the executor with /jobgroup/save .
Queries existing job handlers with /jobinfo/pageList and registers new ones using /jobinfo/add when necessary.
private void addJobGroup(){
if (jobGroupService.preciselyCheck()) return;
if (jobGroupService.autoRegisterGroup())
log.info("auto register xxl-job group success!");
}
private void addJobInfo(){
List
groups = jobGroupService.getJobGroup();
XxlJobGroup group = groups.get(0);
String[] beans = applicationContext.getBeanNamesForType(Object.class,false,true);
for (String beanName : beans){
Object bean = applicationContext.getBean(beanName);
Map
methods = MethodIntrospector.selectMethods(
bean.getClass(),
method -> AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class)
);
for (Map.Entry
entry : methods.entrySet()){
Method m = entry.getKey();
if (!m.isAnnotationPresent(XxlRegister.class)) continue;
XxlRegister reg = m.getAnnotation(XxlRegister.class);
// check existence, then register if absent
}
}
}Auto‑Configuration
A starter module provides XxlJobPlusConfig annotated with @Configuration and @ComponentScan . The configuration class is referenced in META-INF/spring.factories so that it is loaded automatically when the starter is on the classpath.
Testing
After adding the starter dependency, configure the admin address, token, executor name, and the additional properties required by the starter (admin username/password, executor title). Then annotate a method with both @XxlJob and @XxlRegister :
@XxlJob("testJob")
@XxlRegister(cron="0 0 0 * * ? *", author="hydra", jobDesc="测试job")
public void testJob(){
System.out.println("#码农参上");
}Running the application shows the executor and the annotated jobs being created in the XXL‑Job admin UI without any manual steps.
Conclusion
The starter encapsulates all the boiler‑plate required for executor and job registration, allowing developers to focus on business logic while the scheduler configuration is handled automatically.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.