2014-10-27 35 views
0

我想用註解來獲取bean,但它不工作。我想知道爲什麼 ? 這是我的代碼片段:如何獲得所有具有@Entity註釋的bean?

ConfigurableApplicationContext suggestorContext = createContext(「context.xml」); //查找所有@Entities類 Map beansWithAnnotation = suggestorContext.getBeansWithAnnotation(Entity.class);

我的地圖大小爲0 !!!!

這裏是我的context.xml文件:

<?xml version="1.0" encoding="UTF-8" ?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
      http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> 


<bean id="ismDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
     <property name="username" value="user"/> 
     <property name="password" value="password"/> 
     <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> 
    </bean> 

    <bean id="myEmf" 
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> 
     <property name="dataSource" ref="ismDS"/> 
     <property name="jpaVendorAdapter"> 
      <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
       <property name="showSql" value="false"/> 
       <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"/> 
       <property name="generateDdl" value="false"/> 
      </bean> 
     </property> 
     <property name="packagesToScan" value="com.myproject.entities.entity"/> 
    </bean> 


    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> 
     <property name="entityManagerFactory" ref="myEmf"/> 
    </bean> 

    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <bean 
      class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> 

    <bean 
      class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/> 


    <jpa:repositories base-package="com.mypackage.dao" 
      entity-manager-factory-ref="myEmf"/> 

</beans> 

我所有的實體是以下包:com.myproject.entities.entity

有什麼不對嗎?

+0

也許反思會有幫助嗎?你可以得到所有的註釋並檢查必要的 – 2014-10-27 18:38:00

回答

1

它不起作用,因爲spring的getBeansWithAnnotation(Entity.class);將只返回spring bean,但通常的實體不是Spring bean,因此現在可以工作。


也許有一種方法在JPA/Hibernate獲取所有Mapped類(類不是實體實例!!)。

這裏討論了通過一些註釋找到所有類的其他方法:Scanning Java annotations at runtime,其中一個答案中提到了一個名爲「Google reflections」的庫。我前幾次使用這個工具,它運行良好。

相關問題