Singleton vs. dependency injection

I never used the javas-dependent injection function, so I read a few pages about it, and I still don't know about the duel between singleton and dependency injection.

Take a basic example: let's say that I am creating a small Java application using the MVC or MVVM pattern. I would start from the login page, asking for a username and password. These 2 information may be needed later in the application, so I will need to store them in a simple POJO, accessible from any kind of application.

What should I use then? Singleton Or should I insert a POJO constructor and get it if necessary with an injector (e.g. using Guice)?

Thank you for enlightening me :)

+4
source share
2 answers

I would stay away from POJO, which was addicted. In this situation, I would have my ViewModels models with a single-user service that provides / manages your user. If they need the current user, their embedded service provides them with the current corresponding POJO instance. As long as your user management service is wrapped in an interface, so it can be replaced later without breaking functionality, I think it satisfies IoC.

This is how I approached similar issues, I'm not sure if this is the best way to do this, though.

+1
source

Simple POJO should not be injected through dependency injection. It either should not be singleton, since you need to create a new instance for each request.

- "" /// beans/ .. , . .

- , - . getInstance (, singleton pattern) 1 Main . Spring, , beans , .

- , "" .

, .

+1
source

Source: https://habr.com/ru/post/1648339/


All Articles