从扩展CrudRepository <class,id>的接口创建bean?

时间:2016-12-31 01:28:46

标签: hibernate spring-boot spring-data-jpa

我正在按照本教程测试Hibernate,然后将其实现到我的项目中:http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/

我的问题是这条指令要求UserDAO是一个bean:

@Autowired
private UserDao userDao;

它不是......?我觉得我在本网站提供的示例中遗漏了一些非常重要的内容。我曾经使用implements Serializable来实现bean,但在这种情况下不使用它。它应该如何被视为一个bean?

如果有人能向我解释我所缺少的东西,我会非常感激。这种实现CRUD的方式更多只使用接口和标准方式来声明函数看起来非常吸引人。谢谢!

编辑:下面是我的代码。当我尝试将它集成到我的项目中时,教程提供的代码不起作用,因为项目架构的差异(我的猜测)。

架构:http://imgur.com/a/2xsI4

Application.java

@SpringBootApplication
@ComponentScan("boot")
@ComponentScan("dao")
@ComponentScan("modele")
@EnableJpaRepositories("org.utc.ai15")
public class Application {

    public static void main (String[] args){
        SpringApplication.run(Application.class, args);
    }

}

TestDAO.java

@Transactional
@Component 
public interface TestDAO extends CrudRepository<Test, Long > {

  /**
   * This method will find an User instance in the database by its email.
   * Note that this method is not implemented and its working code will be
   * automagically generated from its signature by Spring Data JPA.
   */
  public Test findByEmail(String email);

}

我认为这就是问题所涉及的一切。

我已尝试将@Component添加到 TestDAO.java ,因此会使用@ComponentScan("dao")进行扫描,但它无法正常工作。

这是错误:

Field testDao in boot.controller.TestController required a bean of type 'dao.TestDAO' that could not be found.

编辑2:错误为@EnableJpaRepositories("org.utc.ai15"),正确声明为@EnableJpaRepositories("dao")(参见@Alex答案)。

1 个答案:

答案 0 :(得分:1)

这很可能是由于bean发现/包扫描。

检查以下内容:

  • 确保您的UserDAO低于SpringBootApplication(Spring Boot使用主类作为root来扫描bean)。
  • 或者使用@EnableJpaRepositories(basePackages="org.my.pkg")
  • 定义存储库包
  • 或者您添加@ScanPackages以定义Bean发现的其他包(不仅仅是存储库)。

通过软件包,我的意思是您在课程顶部拥有的内容。