@Autowired entityManagerFactory为空 [英] @Autowired entityManagerFactory is null
问题描述
我的应用无法自动连接entityManagerFactory.
我的 applicationContext.xml :
< tx:注解驱动/>< context:component-scan base-package ="top.level.package"/>< bean id ="persistenceUnitManager"class ="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"><属性名称="persistenceXmlLocation">< value> classpath:jpa-persistence.xml</value></property></bean>< bean id ="entityManagerFactory"class ="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><属性名称="persistenceUnitManager" ref ="persistenceUnitManager"/></bean>< bean id ="transactionManager"class ="org.springframework.orm.jpa.JpaTransactionManager"><属性名称="entityManagerFactory" ref ="entityManagerFactory"/></bean>
我的 java类:
@Component公共类引擎{@Autowired@Qualifier("entityManagerFactory")私有EntityManagerFactory实体管理器工厂;......}
问题:
为什么entityManagerFactory为空?
要让spring使用注释进行自动扭曲,您必须告诉spring.在您的xml配置中(假设您还没有 context:component-scan
元素),添加一个 context:annotation-config
.这将指示Spring应用程序上下文扫描注释(例如 @Autowired
, @Inject
, @Resource
等)以进行自动装配./p>
还要确保要将 EntityManagerFactory
注入到的类( Engine
类)是spring托管bean.Spring只会将引用注入到Spring托管的bean中.
My app can't autowire entityManagerFactory.
My applicationContext.xml:
<tx:annotation-driven/>
<context:component-scan base-package="top.level.package" />
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation">
<value>classpath:jpa-persistence.xml</value>
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
My java class:
@Component
public class Engine {
@Autowired
@Qualifier("entityManagerFactory")
private EntityManagerFactory entityManagerFactory;
......
}
Question:
Why entityManagerFactory is null?
For spring to do autowring using annotations you have to tell spring that. In your xml configuration (assuming you don't already have context:component-scan
element) add a context:annotation-config
. This will instruct the spring application context to scan for annotations (like @Autowired
, @Inject
, @Resource
etc.) to do autowiring.
Also make sure that the class you want the EntityManagerFactory
to be injected into (the Engine
class) is a spring managed bean. Spring will only inject references into spring managed beans.
这篇关于@Autowired entityManagerFactory为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!