Reputation: 1275
I'm just learning Spring coming from a Java background. What I understand dependency injection to be is that you supply the objects it's dependencies, rather than the object initializing its own dependencies. For example:
/*
MyObj depends on HashMap as a dependency.
*/
public class MyObj {
private HashMap hashmap;
public MyObj() {
this.hashmap = new HashMap();
}
}
Instead of doing that, you supply the HashMap
through the constructor.
/*
MyObj depeneds on HashMap as a dependency.
*/
public class MyObj {
private HashMap hashmap;
public MyObj(HashMap hashmap) {
this.hashmap = hashmap;
}
}
This is what I think dependency injection to be. But the way Spring does it is, in my opinion, more code and just messier. In Spring, you have to have this separate method🔛
@Bean
public HashMap hashmap() {
return new HashMap();
}
Then construct the MyObj
object using ApplicationContext.getBean(MyObj.class)
. However, I find many problems
with this method. First of all, in a Swing app, this is how I would initialze the component ui tree maker:
public class ComponentUI {
public ComponentUI(JFrame frame, JPanel panel, ...) {
this.frame = frame;
this.panel = panel;
...
}
}
There are going to be many many components in that constructor. This way, I can construct ComponentUI
by
doing new ComponentUI(...)
and pass in the components. With Spring, however, I have to have a separate
method for each one. That takes a lot of space and a lot of time to make each method. But the problem
I find even worse is that if there are two JPanel
's in the constructor, then you have to create two
separate objects that extend JPanel
. Let me show you what I mean:
public class ComponentUI {
public ComponentUI(..., JPanel panel1, JPanel panel2, ...) {
...
this.panel1 = panel1;
this.panel2 = panel2;
...
}
}
With Spring, I can't do this:
@Bean
public JPanel panel1() {
...
}
@Bean
public JPanel panel2() {
...
}
or else there will be two methods returning the same object, so Spring doesn't know which one to use.
Instead, I have to create my own objects that derive from JPanel
then use that everywhere. In my
Swing app, I have a whole folder of components that derive from other components.
So with these inconveniences in mind, why would I use Spring's dependency injection over regular dependency injection, which is, constructing the object and supplying the objects.
Upvotes: 1
Views: 555
Reputation: 2511
Spring dependency injection does more then what you are showing. When you try to do everything by yourself with real world problem, you will see the pain and then will appreciate the benefits of Spring dependency and i bet you will start using spring in no time.
I am not saying you have to use spring DI but it would make your life easier.
Upvotes: 1