java – PersistenceAnnotationBeanPostProcessor有什么用吗?

前端之家收集整理的这篇文章主要介绍了java – PersistenceAnnotationBeanPostProcessor有什么用吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
根据其 JavaDoc,PersistenceAnnotationBeanPostProcessor似乎负责向EntityManager注入注释@PersistenceContext.这似乎意味着没有这个bean在Spring应用程序上下文xml中声明,@PersistenceContext注释将不起作用.

然而,根据我的实验,这不是事实.

persistence.xml中

  1. <persistence xmlns="http://java.sun.com/xml/ns/persistence"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
  4. http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
  5. version="1.0">
  6. <persistence-unit name="default" transaction-type="RESOURCE_LOCAL" />
  7. </persistence>

Spring应用程序上下文XML

  1. <context:component-scan base-package="com.test.dao" />
  2.  
  3. <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerfactorybean">
  4. <property name="dataSource" ref="dataSource"/>
  5. <property name="persistenceUnitName" value="default"/>
  6. <property name="jpaVendorAdapter">
  7. <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
  8. <property name="showsql" value="true"/>
  9. <property name="generateDdl" value="true"/>
  10. <property name="databasePlatform" value="org.hibernate.dialect.DerbyDialect"/>
  11. </bean>
  12. </property>
  13. </bean>
  14.  
  15. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  16. <property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver"/>
  17. <property name="url" value="jdbc:derby://localhost:1527/c:\derbydb\mydb"/>
  18. <property name="username" value="APP"/>
  19. <property name="password" value="APP"/>
  20. </bean>
  21.  
  22. <tx:annotation-driven/>
  23.  
  24. <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
  25. <property name="entityManagerFactory" ref="entityManagerFactory" />
  26. </bean>
  27.  
  28. <!--
  29. <bean id="persistenceAnnotation" class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
  30. -->

在UserDAOImpl

  1. @Repository("userDao")
  2. public class UserDaoImpl implements UserDao {
  3.  
  4. @PersistenceContext
  5. protected EntityManager entityManager;
  6.  
  7. @Transactional
  8. public void save(User user) {
  9. entityManager.persist(user);
  10. }
  11. }

无论我评论还是取消注释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 /&gt ;.透明地激活.

猜你在找的Java相关文章