Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular Dependency Error for Google Guice with Play2.4 and scala

My application uses Play 2.4 with Scala 2.11 .I started transforming my existing code to make use of Google Guice that comes with Play 2.4 .

When I run my code after making the first set of changes , I found Some DAOs in my code are failing with circular dependency error.

For example I have two DAOs

class BookDAO @Inject()
(protected val personDAO : PersonDAO,
 @NamedDatabase("mysql")protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
...
...
val personId = //some id
personDAO.get(personId)
}

class PersonDAO @Inject()
(protected val bookDAO : BookDAO,
 @NamedDatabase("mysql")protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
...
...
val bookName= //some id
personDAO.getByName(bookName)
}

I got the below error while trying to access either BookDAO or PersonDAO

Tried proxying schema.BookDAO to support a circular dependency, but it is not an interface.
  at schema.BookDAO.class(Books.scala:52)
  while locating schema.BookDAO

Can someone help me resolving this error .

Thanks in advance

like image 464
Bhavya Latha Bandaru Avatar asked Jun 30 '15 13:06

Bhavya Latha Bandaru


1 Answers

Quick solution

Inject a Provider instead:

class BookDAO @Inject()(personDaoProvider: Provider[PersonDAO], ...)
extends HasDatabaseConfigProvider[JdbcProfile] {
  val personDAO = personDaoProvider.get
  def person = personDAO.get(personId)
}

And the same for BookDAO. This will work out of the box. Guice already "knows" how to inject Providers.


Better approach

Decouple the class definition from the implementation. See Mon Calamari's answer.

like image 139
Roman Avatar answered Sep 30 '22 06:09

Roman