Как получить все компоненты, которые имеют аннотацию @Entity?

Я пытаюсь получить бин с аннотацией, но она не работает. Интересно, почему? Вот мой фрагмент кода:

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

Что не так, пожалуйста?

2 ответа

Решение

Это не работает, потому что весна getBeansWithAnnotation(Entity.class); вернет только весенние бины, но обычные сущности не являются бобами Spring, поэтому теперь это работает.


Возможно, в JPA/Hibernate есть способ получить все сопоставленные классы (классы, а не экземпляры сущностей!!).

Здесь обсуждаются другие способы найти все классы по некоторым аннотациям: Сканирование аннотаций Java во время выполнения, в одном из ответов упоминается библиотека под названием " Google отражений". Я использовал этот инструмент несколько раз назад, и он работал хорошо.

Чтобы добавить код, на который указал здесь @Ralph:

        ClassPathScanningCandidateComponentProvider scanner =
        new ClassPathScanningCandidateComponentProvider(false);

  scanner.addIncludeFilter(new AnnotationTypeFilter(Entity.class));

  for (BeanDefinition bd : scanner.findCandidateComponents("com.example.changeme"))
  {
     log.error(bd.getBeanClassName());
  }
Другие вопросы по тегам