我是靠谱客的博主 勤恳薯片,这篇文章主要介绍Spring 中FactoryBean getObject获得空值,现在分享给大家,希望可以做个参考。

这里的JobDetail返回为null

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean public JobDetail printTimeJobDetail(){ JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); // durability 表示任务完成之后是否依然保留到数据库,默认falses jobDetailFactoryBean.setDurability(true); //当Quartz服务被中止后,再次启动或集群中其他机器接手任务时会尝试恢复执行之前未完成的所有任务 jobDetailFactoryBean.setRequestsRecovery(true); jobDetailFactoryBean.setJobClass(MyDetailQuartzJobBean.class); jobDetailFactoryBean.setDescription("打印时间定时器2"); Map<String,String> jobDataAsMap = new HashMap<>(); jobDataAsMap.put("targetObject","printTimeQuartz"); //spring 中bean的名字 jobDataAsMap.put("targetMethod","execute"); //执行方法名 jobDetailFactoryBean.setJobDataAsMap(jobDataAsMap); return jobDetailFactoryBean.getObject(); }

 

我们从JobDetailFactoryBean源码入手,实现了InitializingBean接口,会实现afterPropertiesSet()接口,会在初始化bean的时候执行。

观察源码JobDetail在afterPropertiesSet()方法中产生。之所以上面JobDetail返回空,因为afterPropertiesSet()的执行在上面@Bean 注解的方法后执行。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public void afterPropertiesSet() { Assert.notNull(this.jobClass, "Property 'jobClass' is required"); if (this.name == null) { this.name = this.beanName; } if (this.group == null) { this.group = "DEFAULT"; } if (this.applicationContextJobDataKey != null) { if (this.applicationContext == null) { throw new IllegalStateException("JobDetailBean needs to be set up in an ApplicationContext to be able to handle an 'applicationContextJobDataKey'"); } this.getJobDataMap().put(this.applicationContextJobDataKey, this.applicationContext); } JobDetailImpl jdi = new JobDetailImpl(); jdi.setName(this.name != null ? this.name : this.toString()); jdi.setGroup(this.group); jdi.setJobClass(this.jobClass); jdi.setJobDataMap(this.jobDataMap); jdi.setDurability(this.durability); jdi.setRequestsRecovery(this.requestsRecovery); jdi.setDescription(this.description); this.jobDetail = jdi; }

 

我们可以这样写,并且能够在spring容器中找到JobDetail。这是FactortBean接口帮我们做到的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Bean public JobDetailFactoryBean printTimeJobDetail(){ JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean(); // durability 表示任务完成之后是否依然保留到数据库,默认falses jobDetailFactoryBean.setDurability(true); //当Quartz服务被中止后,再次启动或集群中其他机器接手任务时会尝试恢复执行之前未完成的所有任务 jobDetailFactoryBean.setRequestsRecovery(true); jobDetailFactoryBean.setJobClass(MyDetailQuartzJobBean.class); jobDetailFactoryBean.setDescription("打印时间定时器2"); Map<String,String> jobDataAsMap = new HashMap<>(); jobDataAsMap.put("targetObject","printTimeQuartz"); //spring 中bean的名字 jobDataAsMap.put("targetMethod","execute"); //执行方法名 jobDetailFactoryBean.setJobDataAsMap(jobDataAsMap); return jobDetailFactoryBean; }

 

 

最后

以上就是勤恳薯片最近收集整理的关于Spring 中FactoryBean getObject获得空值的全部内容,更多相关Spring内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(75)

评论列表共有 0 条评论

立即
投稿
返回
顶部