Autowired to hibernate Interceptor

拜拜、爱过 提交于 2019-12-05 02:12:33

问题


I'm extending hibernate.EmptyInterceptor and in my implementation I would like to have autowired to some services but they return null. I added a @Component annotation over the class. My code:

<property name="jpaPropertyMap">
    <map>
        <entry key="javax.persistence.transactionType" value="JTA" />
        <entry key="hibernate.current_session_context_class" value="jta" />
        <entry key="hibernate.transaction.manager_lookup_class"
            value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup" />
        <entry key="hibernate.connection.autocommit" value="false" />
        <entry key="hibernate.ejb.interceptor" value="com.net.filter.AuditInterceptor"/>
    </map>
</property>

and the class :

@SuppressWarnings("serial")
@Component
public class AuditInterceptor extends EmptyInterceptor {

    @Autowired
    private IUserSessionService userSessionService;

回答1:


I know this is probably coming two years too late - but I was searching for an answer for the same problem, and thought this would be useful to someone in the future.

Looking at Hibernate code looks like Hibernate would instantiate a new instance of the interceptor if you give the class name, but if you pass in a bean instance reference it will use that.

So

<bean id="myInterceptor" class="com.net.filter.AuditInterceptor" />

...

<property name="jpaPropertyMap">
    <map>
        <entry key="javax.persistence.transactionType" value="JTA" />
        <entry key="hibernate.current_session_context_class" value="jta" />
        <entry key="hibernate.transaction.manager_lookup_class"
            value="com.atomikos.icatch.jta.hibernate3.TransactionManagerLookup" />
        <entry key="hibernate.connection.autocommit" value="false" />
        <entry key="hibernate.ejb.interceptor" >
            <ref bean="myInterceptor" />
        </entry>
    </map>
</property>

Now the bean myInterceptor is Spring managed and autowiring will work!




回答2:


Spring will never leave a @Autowired target as null (unless null is what you are injecting). That should tell you that if an @Autowired field is null, then Spring had nothing to do with it.

It seems that is the case here. By providing something like

<entry key="hibernate.ejb.interceptor" value="com.net.filter.AuditInterceptor"/>

I believe you're telling Hibernate to create that instance itself and it therefore won't be a Spring managed bean.

If you post the rest of the bean definition because I don't know what bean you are trying to inject into, there might be alternatives.



来源:https://stackoverflow.com/questions/21114164/autowired-to-hibernate-interceptor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!