Spring没有找到Repository注释类

时间:2016-10-19 15:03:52

标签: java spring spring-data-jpa

我有一个带有域和持久层的spring应用程序。在我的持久层中,我有以下形式的DAO:

    public interface PersonDAO {
       public void addPerson(Person person);
       public void updatePerson(Person person);
       public List<Person> listPersons();
       public Person getPersonById(int id);
    }

实施:

    @Repository
    public class PersonDAOImpl implements PersonDAO {
        @PersistenceUnit(unitName = "entityManagerFactory")
        private EntityManagerFactory ENITY_MANAGER_FACTORY;

        public PersonDAOImpl(){}

        @Override
        public void addPerson(Person person) {
            EntityManager entityManager = ENITY_MANAGER_FACTORY.createEntityManager();
           ...
        }
        ...
   }

我的春季Java Config文件:

@Configuration
@EnableJpaRepositories("xx.xx.xxxxx.persistence")
public class PersistenceConfig {
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(DataSource dataSource,
                                                                               JpaVendorAdapter vendorAdapter,
                                                                               LoadTimeWeaver loadTimeWeaver) {

      ...
    }

    @Bean
    public DataSource dataSource() {
        ...
    }

    @Bean
    public JpaVendorAdapter vendorAdapter() {
        ...
    }
    ...
   }

配置中的所有bean都正确加载,但是当我在main中调用它时,PersonDAOImpl bean根本不加载:

public class ManagePersons {
    private static EntityManagerFactory ENTITY_MANAGER_FACTORY;

    public static void main(String [] args){

        ApplicationContext ctx = new AnnotationConfigApplicationContext(PersistenceConfig.class);

        ENTITY_MANAGER_FACTORY = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);

        PersonDAO personDAO = ctx.getBean(PersonDAO.class);
      ...
 }
}

它抛出:

Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [xx.xx.xxxxx.persistence.PersonDAO] is defined

2 个答案:

答案 0 :(得分:1)

PersonDAO应扩展JpaRepository的子接口,将其作为jpa存储库进行扩展@EnableJpaRepositories

public interface PersonDAO extends Repository<Person, Integer> {
    public void addPerson(Person person);
    public void updatePerson(Person person);
    public List<Person> listPersons();
    public Person getPersonById(Integer id);
}

请参阅http://docs.spring.io/spring-data/jpa/docs/1.6.6.RELEASE/reference/html/repositories.html

答案 1 :(得分:0)

我首先尝试以下方法:

@EnableJpaRepositories(basePackages = "xx.xx.xxxxx.persistence")

而不是

@EnableJpaRepositories("xx.xx.xxxxx.persistence")