在Job中Spring注入的bean实例,bean实例使用了hibernate出现no session有关问题的解决办法
因为bean实例使用了hibernate去访问数据库,而且象关系映射使用延迟的对象初始化(也就是说,如果有某一个hibernate请求不是经由web request发起的,而是由quartz这样的定时任务发起的,那么quartz怎么样才能得到hibernate session呢?)
spring配置:
<bean >
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- Manager template -->
<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
<property name="preInterceptors">
<list>
<ref bean="hibernateInterceptor"/>
</list>
</property>
</bean>
<!-- 配置令columnService的方法在quartz的job中支持延迟加载 -->
<bean id="quartzColumnService" parent="txProxyTemplate" >
<property name="target" ref="columnService"/>
</bean>
<!-- 配置令indexPageService的方法在quartz的job中支持延迟加载 -->
<bean id="quartzIndexPageService" parent="txProxyTemplate" >
<property name="target" ref="indexPageService"/>
</bean>
<bean >
<property name="tagClassMap" ref="tagMap" />
<property name="siteService" ref="siteService" />
</bean>
这样一来,在job中就可以使用quartzIndexPageService和quartzColumnService这两个bean了,而且这两个bean的实现indexPageService和columnService中使用hibernate(就算hibernate对象使用延迟初始化)查询而不会引起no session 异常。