Consider 2 classes, Student and Subject.
Case 1 :
class Student
{
private final Subject subject;
Student (final Subject subject)
{
this.subject = subject;
}
//do something
}
Case 2 :
import javax.inject.Inject;
class Student
{
private final Subject subject;
@Inject
Student (final Subject subject)
{
this.subject = subject;
}
//do something
}
Can someone explain the difference between these two cases, and when each case is used?
Basically there is no difference in the behavior of the class (methods are the same and contain the same code) and the information that this class maintains (data fields are the same).
But this class doesn't "live" in vacuum, probably its a part of an application that contains many other classes, and you have somehow to manage the classes, dependencies between them, and so forth. So here comes the difference:
The difference is how do you organize the application, more precisely who "Manages" this class, read, who creates it (calls new Student
) and who is responsible for "figuring out" where to "get" the instance of class Subject that the object of type Student obviously must be supplied with in order to get instantiated properly.
So there are many ways to manage your code in this sense:
You can do everything by yourself:
main() {
Subject subject = new Subject()
Student student = new Student(subject)
}
Now if there are say 1000 classes, you'll have to maintain 1000 lines of code to create all these objects. Although In this case, it might still seem doable, because objects are created together, but sometimes the real applications can be much more complicated than that, the dependency resolution may also become much more complicated.
Hence there were created DI containers like Guice, Spring and so forth:
They can figure out by themselves how to instantiate the classes, analyze the class's structure to figure out the dependencies and bottom line create the classes for your.
To provide the "hints" to these containers you can use annotations like @Inject
but all-in-all, you manage the application in a different way:
new Student, new Subject()
, etc. Dependency injection container does it for you.Basically its a very broad topic, so for educational purposes I suggest you to find a comprehensive tutorial about this DI topic even before you dive into the particular implementation technicalities (like @Inject
in Google Guice).