此处以@xxlJob注解举例
**1、实现 SmartInitializingSingleton, ApplicationContextAware **
2、MethodIntrospector.selectMethods()获取类方法
@Configuration
public class XxlJobConfig implements SmartInitializingSingleton, ApplicationContextAware {
private Logger logger = LoggerFactory.getLogger(XxlJobConfig.class);
private ApplicationContext applicationContext;
@Value("${xxl.job.admin.addresses}")
private String adminAddresses;
@Value("${xxl.job.accessToken}")
private String accessToken;
@Value("${xxl.job.executor.appname}")
private String appname;
@Value("${xxl.job.executor.address}")
private String address;
@Value("${xxl.job.executor.ip}")
private String ip;
@Value("${xxl.job.executor.port}")
private int port;
@Value("${xxl.job.executor.logpath}")
private String logPath;
@Value("${xxl.job.executor.logretentiondays}")
private int logRetentionDays;
@Bean
public XxlJobSpringExecutor xxlJobExecutor() {
logger.info(">>>>>>>>>>> xxl-dispatch config init.");
XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
xxlJobSpringExecutor.setAdminAddresses(adminAddresses);
xxlJobSpringExecutor.setAppname(appname);
xxlJobSpringExecutor.setAddress(address);
xxlJobSpringExecutor.setIp(ip);
xxlJobSpringExecutor.setPort(port);
xxlJobSpringExecutor.setAccessToken(accessToken);
xxlJobSpringExecutor.setLogPath(logPath);
xxlJobSpringExecutor.setLogRetentionDays(logRetentionDays);
return xxlJobSpringExecutor;
}
@Override
public void afterSingletonsInstantiated() {
String[] beanNamesForType = applicationContext.getBeanNamesForType(Object.class, false, false);
for (String s : beanNamesForType) {
Object bean = applicationContext.getBean(s);
Map<Method, XxlJob> selectMethods = MethodIntrospector.selectMethods(bean.getClass(), (MethodIntrospector.MetadataLookup<XxlJob>) method -> {
return AnnotatedElementUtils.findMergedAnnotation(method, XxlJob.class);
});
if (MapUtil.isEmpty(selectMethods)) {
continue;
}
for (Map.Entry<Method, XxlJob> entry : selectMethods.entrySet()) {
XxlJob value = entry.getValue();
Method key = entry.getKey();
xxlJobMap.put(value.value(), key);
}
}
}
private ConcurrentHashMap<String, Method> xxlJobMap = new ConcurrentHashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}