为了记录,我会发布我的答案。
我试图扩展@AlexanderArendar 的实验:
import javax.inject.Singleton
/**
* Created by Alex on 7/27/2016.
*/
@Singleton
class JustASingleton {
def giveMeFive = "5"
}
第一个控制器
class MainController @Inject()(
environment:play.api.Environment,
documentService:DocumentService,
userService:UserService,
singletonInstance:JustASingleton
)(implicit ec:ExecutionContext)extends Controller {
def testSingletonInjection() = Action(Ok("controller id " + System.identityHashCode(this).toString + " and Injected Bean id " + System.identityHashCode(singletonInstance).toString))
...
第二控制器
class SecondController @Inject()(
environment:play.api.Environment,
documentService:DocumentService,
userService:UserService,
singletonInstance:JustASingleton
)(implicit ec:ExecutionContext)extends Controller {
def testSingletonInjection() = Action(Ok("controller id " + System.identityHashCode(this).toString + " and Injected Bean id " + System.identityHashCode(singletonInstance).toString))
...
然后在路线中
GET /singletonX controllers.MainController.testSingletonInjection
GET /singletonY controllers.SecondController.testSingletonInjection
调用这两个端点给了我以下结果:
controller id 1944357758 和 Injected Bean id 853668078
controller id 943948501 和 Injected Bean id 853668078
我可以根据测试得出结论,可以将具体类创建为单例,而无需提供接口