SpringBoot整合quartz后job中无法注入service问题修改后导致job中无法使用构造器注入的问题解决办法

一.问题背景

1.1 环境

  • spring-boot 2.1.0.RELEASE
  • spring-boot-starter-quartz 2.1.0.RELEASE

1.2 解决job中无法注入bean

这个问题网上一搜索一堆教程,大致意思就是需要自定义一个JobFactory,继承org.springframework.scheduling.quartz.AdaptableJobFactory,然后重写其中的createJobInstance方法以达到注入的目的.

代码如下:

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

@Component
public class AutowiredableJobFactory extends AdaptableJobFactory
{
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) {
        // 实例化对象
        Object jobInstance = super.createJobInstance(bundle);
        // 进行注入(Spring管理该Bean)
        capableBeanFactory.autowireBean(jobInstance);
        //返回对象
        return jobInstance;
    }
}

然后就解决了在job中@Autowired的对象会是null的问题了.

1.3 新的问题

但是这样会有一个问题,在新版IDEA中,如果你使用@Autowired注解来注入,会给出如下提示

Field injection is not recommended

为什么会提示这个呢?百度一下,得到的答案是这样:

使用变量依赖注入的方式是不被推荐的

Always use constructor based dependency injection in your beans. Always use assertions for mandatory dependencies

推荐使用构造器强制注入

那么,当我选择这种推荐写法后,代码如下

@Component
public class DemoTask implements Job {
	private final DemoService demoService;
	
	public DemoTask(DemoService demoService){
		this.demoService = demoService;
	}
}

在启动的时候,报了如下错误

org.quartz.SchedulerException: Job instantiation failed
 at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:47)
 at org.quartz.core.JobRunShell.initialize(JobRunShell.java:127)
 at org.quartz.core.QuartzSchedulerThread.run(QuartzSchedulerThread.java:392)
Caused by: java.lang.NoSuchMethodException: DemoTask.<init>()
 at java.lang.Class.getConstructor0(Class.java:3082)
 at java.lang.Class.getDeclaredConstructor(Class.java:2178)
 at org.springframework.util.ReflectionUtils.accessibleConstructor(ReflectionUtils.java:524)
 at org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance(AdaptableJobFactory.java:61)
 at AutowiredableJobFactory.createJobInstance(AutowiredableJobFactory.java:19)
 at org.springframework.scheduling.quartz.AdaptableJobFactory.newJob(AdaptableJobFactory.java:43)
 ... 2 common frames omitted

二. 一种解决方法

2.1 为什么不可以使用构造器注入

报了错误后,不影响程序启动,但是该定时任务初始化失败了,无法被执行.将构造器注入改为@Autowired变量注入后,启动无报错,定时器初始化成功.

那么,为什么不可以使用构造器注入呢?

根据报错的堆栈,我们来看一下org.springframework.scheduling.quartz.AdaptableJobFactory.createJobInstance的代码

	/**
	 * Create an instance of the specified job class.
	 * <p>Can be overridden to post-process the job instance.
	 * @param bundle the TriggerFiredBundle from which the JobDetail
	 * and other info relating to the trigger firing can be obtained
	 * @return the job instance
	 * @throws Exception if job instantiation failed
	 */
	protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
		Class<?> jobClass = bundle.getJobDetail().getJobClass();
		return ReflectionUtils.accessibleConstructor(jobClass).newInstance();
	}

然后继续往下,看到

	/**
	 * Obtain an accessible constructor for the given class and parameters.
	 * @param clazz the clazz to check
	 * @param parameterTypes the parameter types of the desired constructor
	 * @return the constructor reference
	 * @throws NoSuchMethodException if no such constructor exists
	 * @since 5.0
	 */
	public static <T> Constructor<T> accessibleConstructor(Class<T> clazz, Class<?>... parameterTypes)
			throws NoSuchMethodException {

		Constructor<T> ctor = clazz.getDeclaredConstructor(parameterTypes);
		makeAccessible(ctor);
		return ctor;
	}

这里我们可以看到,因为参数类型我们在上一步并没有传,只传了一个class到accessibleConstructor中,它匹配不到无参构造方法,就会报NoSuchMethoadException.具体位置在

    @CallerSensitive
    public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException {
        checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);
        return getConstructor0(parameterTypes, Member.DECLARED);
    }
private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
                                        int which) throws NoSuchMethodException
    {
        Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
        for (Constructor<T> constructor : constructors) {
            if (arrayContentsEq(parameterTypes,
                                constructor.getParameterTypes())) {
                return getReflectionFactory().copyConstructor(constructor);
            }
        }
        throw new NoSuchMethodException(getName() + ".<init>" + argumentTypesToString(parameterTypes));
    }
 private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
        if (a1 == null) {
            return a2 == null || a2.length == 0;
        }

        if (a2 == null) {
            return a1.length == 0;
        }

        if (a1.length != a2.length) {
            return false;
        }

        for (int i = 0; i < a1.length; i++) {
            if (a1[i] != a2[i]) {
                return false;
            }
        }

        return true;
    }

所以,我们用网上搜索的这种使用autowireBean()接口来实现注入的方法,跟构造器注入是有冲突的.如果是使用变量注入,则无需更换方法.

那么,如果一定要使用构造器注入呢?

2.2 如何修改JobFactory

既然autowireBean()方法不行,那么再看看还有没有其他路子可以注入的.翻看org.springframework.beans.factory.config.AutowireCapableBeanFactory代码,发现在autowireBean下面还有一个方法,叫autowire.代码如下

/**
	 * Instantiate a new bean instance of the given class with the specified autowire
	 * strategy. All constants defined in this interface are supported here.
	 * Can also be invoked with {@code AUTOWIRE_NO} in order to just apply
	 * before-instantiation callbacks (e.g. for annotation-driven injection).
	 * <p>Does <i>not</i> apply standard {@link BeanPostProcessor BeanPostProcessors}
	 * callbacks or perform any further initialization of the bean. This interface
	 * offers distinct, fine-grained operations for those purposes, for example
	 * {@link #initializeBean}. However, {@link InstantiationAwareBeanPostProcessor}
	 * callbacks are applied, if applicable to the construction of the instance.
	 * @param beanClass the class of the bean to instantiate
	 * @param autowireMode by name or type, using the constants in this interface
	 * @param dependencyCheck whether to perform a dependency check for object
	 * references in the bean instance (not applicable to autowiring a constructor,
	 * thus ignored there)
	 * @return the new bean instance
	 * @throws BeansException if instantiation or wiring failed
	 * @see #AUTOWIRE_NO
	 * @see #AUTOWIRE_BY_NAME
	 * @see #AUTOWIRE_BY_TYPE
	 * @see #AUTOWIRE_CONSTRUCTOR
	 * @see #AUTOWIRE_AUTODETECT
	 * @see #initializeBean
	 * @see #applyBeanPostProcessorsBeforeInitialization
	 * @see #applyBeanPostProcessorsAfterInitialization
	 */
	Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;

这里,关于第二个参数的取值,在该类中也有定义

/**
	 * Constant that indicates no externally defined autowiring. Note that
	 * BeanFactoryAware etc and annotation-driven injection will still be applied.
	 * @see #createBean
	 * @see #autowire
	 * @see #autowireBeanProperties
	 */
	int AUTOWIRE_NO = 0;

	/**
	 * Constant that indicates autowiring bean properties by name
	 * (applying to all bean property setters).
	 * @see #createBean
	 * @see #autowire
	 * @see #autowireBeanProperties
	 */
	int AUTOWIRE_BY_NAME = 1;

	/**
	 * Constant that indicates autowiring bean properties by type
	 * (applying to all bean property setters).
	 * @see #createBean
	 * @see #autowire
	 * @see #autowireBeanProperties
	 */
	int AUTOWIRE_BY_TYPE = 2;

	/**
	 * Constant that indicates autowiring the greediest constructor that
	 * can be satisfied (involves resolving the appropriate constructor).
	 * @see #createBean
	 * @see #autowire
	 */
	int AUTOWIRE_CONSTRUCTOR = 3;

	/**
	 * Constant that indicates determining an appropriate autowire strategy
	 * through introspection of the bean class.
	 * @see #createBean
	 * @see #autowire
	 * @deprecated as of Spring 3.0: If you are using mixed autowiring strategies,
	 * prefer annotation-based autowiring for clearer demarcation of autowiring needs.
	 */
	@Deprecated
	int AUTOWIRE_AUTODETECT = 4;

是不是很熟悉啊?这不就是Spring自动装配的五种方式吗?

  • no 默认情况下为手动装配

  • by_name 根据属性名称自动装配

  • by_type 根据数据类型自动装配

  • constructor 根据构造函数进行自动装配

  • autodetect 如果找到构造函数,则使用构造函数进行自动装配;否则,使用按类型自动装配

其中,autodetect方式已经遗弃了.但是还是可以使用的,我这里使用的就是这种方式.如果你的项目中全部使用的是构造器注入的话,应该可以使用constructor方式.

修改后的AutowiredableJobFactory如下

import org.quartz.spi.TriggerFiredBundle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.scheduling.quartz.AdaptableJobFactory;
import org.springframework.stereotype.Component;

@Component
public class AutowiredableJobFactory extends AdaptableJobFactory
{
    @Autowired
    private AutowireCapableBeanFactory capableBeanFactory;

    @Override
    protected Object createJobInstance(TriggerFiredBundle bundle) {
        // 获取到需要注入的class
        Class<?> clazz = bundle.getJobDetail().getJobClass();
        // 进行注入
        return capableBeanFactory.autowire(clazz, 4, true);
    }
}

三.总结

这是一次很不一样的体验.因为发现报错后就去网上搜索了一下,发现没有搜到相关的解释,教程.但自己又想知道为什么会导致构造器注入无法使用以及如何做才能让它能使用推荐的构造器注入方法.就自己看代码,去问大佬.一步步去发现,很nice.

2020/01/13
Slicenfer

当在 Job注入 Spring Bean 时,需要使用 Spring 提供的 JobFactory 来创建 Job 实例,这样 Job的 Bean 才能被正确注入。具体实现步骤如下: 1. 创建一个实现了 SpringJobFactory 接口的类,用于创建 Job 实例。 ```java import org.quartz.Job; import org.quartz.Scheduler; import org.quartz.SchedulerContext; import org.quartz.spi.JobFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class AutowiringSpringBeanJobFactory implements JobFactory { @Autowired private ApplicationContext context; /** * {@inheritDoc} */ @Override public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException { final Job job = (Job) context.getBean(bundle.getJobDetail().getJobClass()); final SchedulerContext schedulerContext = scheduler.getContext(); schedulerContext.put("applicationContext", context); return job; } } ``` 2. 在 Quartz 配置注册 JobFactory,如下所示: ```java import javax.sql.DataSource; import org.quartz.JobDetail; import org.quartz.Scheduler; import org.quartz.Trigger; import org.quartz.impl.StdSchedulerFactory; import org.quartz.impl.jdbcjobstore.JobStoreTX; import org.quartz.impl.jdbcjobstore.PostgreSQLDelegate; import org.quartz.impl.jdbcjobstore.StdJDBCDelegate; import org.quartz.impl.jdbcjobstore.StdJDBCJobStore; import org.quartz.impl.jdbcjobstore.oracle.OracleDelegate; import org.quartz.spi.JobFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; @Configuration public class QuartzConfig { @Autowired private Environment env; @Bean public JobFactory jobFactory(ApplicationContext applicationContext) { AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory(); jobFactory.setApplicationContext(applicationContext); return jobFactory; } @Bean public Scheduler scheduler(Trigger[] triggers, @Qualifier("quartzDataSource") DataSource dataSource) throws SchedulerException { StdSchedulerFactory factory = new StdSchedulerFactory(); factory.initialize(quartzProperties()); Scheduler scheduler = factory.getScheduler(); scheduler.setJobFactory(jobFactory); scheduler.setDataSource(dataSource); scheduler.setQuartzProperties(quartzProperties()); scheduler.start(); for (Trigger trigger : triggers) { scheduler.scheduleJob(trigger.getJobDetail(), trigger); } return scheduler; } @Bean public JobDetail jobDetail() { return JobBuilder.newJob().ofType(MyJob.class) .storeDurably().withIdentity("MyJob").withDescription("Invoke My Job service...").build(); } @Bean public Trigger trigger(JobDetail job) { return TriggerBuilder.newTrigger().forJob(job) .withIdentity("MyJobTrigger").withDescription("My Job trigger").withSchedule(CronScheduleBuilder.cronSchedule(env.getProperty("myjob.cron.expression"))).build(); } @Bean public Properties quartzProperties() { Properties properties = new Properties(); properties.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, env.getProperty("scheduler.instance.name")); properties.setProperty(StdSchedulerFactory.PROP_SCHED_INSTANCE_ID, env.getProperty("scheduler.instance.id")); properties.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_CLASS, env.getProperty("scheduler.threadPool.class")); properties.setProperty(StdSchedulerFactory.PROP_THREAD_POOL_THREAD_COUNT, env.getProperty("scheduler.threadPool.threadCount")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_CLASS, env.getProperty("scheduler.jobStore.class")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_DRIVER_DELEGATE_CLASS, env.getProperty("scheduler.jobStore.driverDelegateClass")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_USE_PROPERTIES, env.getProperty("scheduler.jobStore.useProperties")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_DATASOURCE, env.getProperty("scheduler.jobStore.dataSource")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_TABLE_PREFIX, env.getProperty("scheduler.jobStore.tablePrefix")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_IS_CLUSTERED, env.getProperty("scheduler.jobStore.isClustered")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_CLUSTER_CHECKIN_INTERVAL, env.getProperty("scheduler.jobStore.clusterCheckinInterval")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_MAX_MISFIRES_TO_HANDLE_AT_A_TIME, env.getProperty("scheduler.jobStore.maxMisfiresToHandleAtATime")); properties.setProperty(StdSchedulerFactory.PROP_JOB_STORE_MISFIRE_THRESHOLD, env.getProperty("scheduler.jobStore.misfireThreshold")); return properties; } } ``` 3. 在 Job注入 Bean,如下所示: ```java import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Component; @Component public class MyJob implements Job { @Autowired private MyService myService; /** * {@inheritDoc} */ @Override public void execute(JobExecutionContext context) throws JobExecutionException { ApplicationContext applicationContext = (ApplicationContext) context.getScheduler().getContext().get("applicationContext"); applicationContext.getAutowireCapableBeanFactory().autowireBean(this); myService.doSomething(); } } ``` 通过这种方式,就可以在 QuartzJob注入 Spring Bean。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值