[英]Unable autowire SessionFactory[null] into @Transactional bean
將Hibernate SessionFactory bean自動裝配到Service中時,我遇到了一個非常奇怪的問題。
我可以在Spring Context對象中找到SessionFactory bean。 因此,創建此類bean沒有問題。 但是,當使用@Transactional
批注標記該bean時,我無法將其自動連線到我的服務中。 工廠字段為null
。 刪除此注釋后-一切正常。
服務等級:
@Service
@Transactional
public class ExampleRunner implements Runnable{
@Autowired
SessionFactory sessionFactory;
...
}
applicationContext.xml中:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:property-placeholder location="classpath:application.properties"
ignore-resource-not-found="true" />
<context:component-scan base-package="org.edu" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"
value="${jdbc.driverClassName:org.hsqldb.jdbcDriver}" />
<property name="url" value="${jdbc.url:jdbc:hsqldb:mem:myAppDb}" />
<property name="username" value="${jdbc.username:sa}" />
<property name="password" value="$jdbc.password:}" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="org.edu" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
${hibernate.dialect:org.hibernate.dialect.HSQLDialect}
</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto:create-drop}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:true}</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"
proxy-target-class="true" />
<bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
用法:
public static void main(String[] args) {
Runnable runner = new ClassPathXmlApplicationContext("applicationContext.xml").getBean(ExampleRunner.class);
runner.run();
}
好像當我將@Transactional
用作類級別注釋時,Spring創建了SessionFactory字段為null
CGLib代理bean。 但是,當我使用@Transational
作為方法級別的注釋時,一切都很好。
所以我只想了解這種行為。 我從Spring文檔中錯過了什么?
我使用Spring 4.1.4.RELEASE。
我實際上得到了您的錯誤,為什么在這里出現問題,因為在使用java Main方法時,您不允許容器為您自動接線bean,這不會自動接線bean,這就是您得到錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.