本文是为了解决发布quartz定时任务时出现NotSerializableException(不能被序列化异常)的问题。
先看看错误代码:
Caused by: java.io.NotSerializableException: Unable to serialize JobDataMap for insertion into database because the value of property 'simpleService' is not serializable: mips.encodeRelationManage.service.impl.TBarcodePackedServiceImpl
at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.serializeJobData(StdJDBCDelegate.java:3355)
at org.quartz.impl.jdbcjobstore.StdJDBCDelegate.insertJobDetail(StdJDBCDelegate.java:512)
at org.quartz.impl.jdbcjobstore.JobStoreSupport.storeJob(JobStoreSupport.java:1126)
... 56 more
错误提示说JobDataMap不能被序列化。
我在很多地方也搜索到类似的问题,比较集中的说法是spring的bug和兼容性问题。
参阅:
1. 求助:quarz+spring启动报错的问题: http://bbs.csdn.net/topics/390375985
2. 解决Spring中使用quartz发生NotSerializableException methodInvoker的问题: http://wangcheng.iteye.com/blog/469344
3. Spring+Quartz 集群: http://soulshard.iteye.com/blog/337886/
但今天我要说的可不是这个问题。
我们在看看错误提示:JobDataMap不能被序列化,因为simpleService不能被序列化,而更上一层的原因是TBarcodePackedServiceImpl(这是我的一个业务service实现类)不能被序列化。
不知道到这里你是否会有灵光一现的感觉?
熟悉序列化机制的朋友都知道,序列化对象时,会把他的属性都一并序列化。这样就会形成一个链式结构,逐级序列化到基本数据类型。
而有时我们并不想让它一直序列化下去,所以只要将不需要序列化的属性添加transient修饰符即可。
例如:
protected transient Log logger = LogFactory.getLog(this.getClass());
private transient TBarcodePackedServiceI tBarcodePackedService;
记住:transient ——临时的
好了,希望对各位有帮助。