根据其
JavaDoc,PersistenceAnnotationBeanPostProcessor似乎负责向EntityManager注入注释@PersistenceContext.这似乎意味着没有这个bean在Spring应用程序上下文xml中声明,@PersistenceContext注释将不起作用.
然而,根据我的实验,这不是事实.
persistence.xml中
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="default" transaction-type="RESOURCE_LOCAL" /> </persistence>
Spring应用程序上下文XML
<context:component-scan base-package="com.test.dao" /> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerfactorybean"> <property name="dataSource" ref="dataSource"/> <property name="persistenceUnitName" value="default"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showsql" value="true"/> <property name="generateDdl" value="true"/> <property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/> </bean> </property> </bean> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/> <property name="url" value="jdbc:derby://localhost:1527/c:\derbydb\mydb"/> <property name="username" value="APP"/> <property name="password" value="APP"/> </bean> <tx:annotation-driven/> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <!-- <bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> -->
在UserDAOImpl
@Repository("userDao") public class UserDaoImpl implements UserDao { @PersistenceContext protected EntityManager entityManager; @Transactional public void save(User user) { entityManager.persist(user); } }
无论我评论还是取消注释persistenceAnnotation bean,结果是一样的.离开这个bean并不会伤害它,但是这个bean有什么用?
我使用的是Spring 3.0.5.
有人会提供一个场景,取出这个bean会导致失败?
另外我也不喜欢创建一个空的持久化单元来愚弄Spring.幸运的是,这个问题已经在Spring 3.1.0中解决了.
解决方法
PersistenceAnnotationBeanPostProcessor由< context:component-scan />透明地激活元件.确切地说,它是< context:annotation-config />元素,它激活bean,但是这个元素又被< context:component-scan /> ;.透明地激活.