我的应用程序不能自动显示entityManagerFactory。
我的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>我的java类
@Component
public class Engine {
@Autowired
@Qualifier("entityManagerFactory")
private EntityManagerFactory entityManagerFactory;
......
}问题:
为什么entityManagerFactory是空的?
发布于 2013-08-24 08:09:16
对于spring,要使用注释进行自动生成,您必须告诉spring。在您的xml配置中(假设您还没有context:component-scan元素)添加一个context:annotation-config。这将指示spring应用程序上下文扫描注释(如@Autowired、@Inject、@Resource等)。去做自动装配。
还要确保您希望将EntityManagerFactory注入( Engine类)的类是一个spring。Spring只会将引用注入spring托管bean。
发布于 2013-08-23 21:08:17
你试过这个吗?
private EntityManagerFactory entityManagerFactory;
@Autowired
@PersistenceUnit(unitName = "myUnitName")
public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
this.entityManagerFactory = entityManagerFactory;
}不久前我也犯了同样的错误,我发现这是一个解决方案。
发布于 2013-08-24 09:37:33
如果您在Engine中使用new Engine() (如您的注释中所述),那么它不是由Spring来管理的。因此,@Component没有任何效果,也不会注入依赖项。你得注射引擎。
https://stackoverflow.com/questions/18411803
复制相似问题