Reputation: 2827
Sorry for this post but I'm a bit confused about IoC and dependency Injection. I'll give you an example what I've in mind but it's hard to implement.
Suppose I have a class user like this:
public class User {
private String username;
private String password;
// getter and setter
}
This class, should be used in several other controller:
Here we have only some example where the User is needed, so in first instance User is a singleton and should "live" in entire application.
On application startup (main) user will be loaded but only one of this three controller will be created. The other component will be created when the application run (and some event occurs).
One simple approach could be to create all this three component to accept an User
object and implement in this way:
public class FirstComponent {
private User user;
public FirstComponent(User user) {
this.user = user;
}
}
In this way, we need to create ALL the component after the user is setup, and not when they are needed.
A better approach (i think...) could be do Inject the user in all the classes this is needed, without be "obbligated" to create this component after the User
is created:
public class FirstComponent {
@Inject
private User user;
public FirstComponent() {
// do something
}
}
public class SecondComponent {
@Inject
private User user;
public SecondComponent(int anArg ) {
// do something
}
}
My question is
In an application, could exists many classes like User, for example:
Sorry if i have posted a stupid question, but looking on the net i'havent found some examples that exaplain how to solve this problem.
I was looking with Guice and I've started to use it a little (very little) but the problem is not solved.
Many thanks for the help!
Upvotes: 0
Views: 329
Reputation: 146
One simple approach could be to create all this three component to accept an User object and implement in this way:
public class FirstComponent {
private User user;
public FirstComponent(User user) {
this.user = user;
}
}
In this way, we need to create ALL the component after the user is setup, and not when they are needed.
That is just not true. This simple approach is what dependency injection is all about. The trick is to chose the right scope for your User
object.
Basically whenever you create a class and you write a new
somewhere add the Object you wanted to create as an Argument to the constructor. An exception would be Containers like a List
or an Array
. This way all the Dependencies are gone.
The problem is that you might end up with a ton of Singleton
Objects and to avoid that you can create Builder
classes that steer the way through Object creation.
This way the creation process is independant from the class logic and the classes will be way easier to unit test with mocked objects.
Upvotes: 1