Playframework 2.4 Singletons, Object

679 Views Asked by At

Before Playframework 2.4 I used create object for singleton class, and now I see than Singletons can be achieved using the @Singleton annotation.

But, what is the difference?

Is only for using a dependency injection with @Inject() ?

I am afraid that Playframework 2.4 with dependency Injection enter in an unnecessarily complicated way.

1

There are 1 best solutions below

0
Roman On BEST ANSWER

@Singleton is part of the JSR 330 standard and is indeed for dependency injection only. It tells your DI framework to create only one instance of the given class and use that single instance across your application. From the docs:

New instances are created every time a component is needed. If a component is used more than once, then, by default, multiple instances of the component will be created. If you only want a single instance of a component then you need to mark it as a singleton.

You can think of it as a directive to your DI framework to create only one instance. Nothing holds you back from creating multiple @Singleton annotated classes by hand using new.

Singleton objects in scala in contrast are true singletons and cannot be instantiated by hand.