BE Study 11th
Dependency Injection.
Dependency Injection is that, the Dependency is injected in the runtime, not the compile time.
For example,
class HelloFactory()
{
private Helloer helloer = new HelloerImpl();
public HelloFactory() { ... }
public sayHello()
{
helloer.sayHello();
}
}
The above looks descent(delegation pattern). However, the problem is that the class HelloFactory is depending on the class HelloerImpl() in the compile time.
class HelloFactory()
{
private final Helloer helloer;
public HelloFactory(Helloer helloer)
{
this.helloer = helloer;
}
public sayHello()
{
helloer.sayHello();
}
}
The above code is much better, because you can inject the dependency(of helloer) in the runtime like
helloFactory = HelloFactory(new HelloerImpl helloer).
Thus, it is great that you eliminated the compile-time dependency.
There are 3 different types of Dependency Injections.
1. Constructor Injections
class HelloFactory()
{
private final Helloer helloer;
public HelloFactory(Helloer helloer)
{
this.helloer = helloer;
}
public sayHello()
{
helloer.sayHello();
}
}
It looks like above. The key is literally that the Injection has occurred within the Constructor; public HelloFactory(Helloer helloer). It is most RECOMMENDED style of DI. One advantage of the style is that it can also set the attribute(the handler to be injected) as final.
You might think defining the constructor is a nuisance. For such people, there's an annotation @RequiredArgsConstructor. With the annotation, lombok creates an constructor that initializes all the final attributes.
2. Method Injection
class HelloFactory()
{
private Helloer helloer;
public HelloFactory()
{
}
public void setHelloer(Helloer helloer)
{
this.helloer = helloer;
}
public sayHello()
{
helloer.sayHello();
}
}
Method Injection literally means that the dependency is injected via 'method'. Usually, the method is setter. It isn't recommended these days because the handler is mutable, and also it can cause circular dependencies.
3. Field Injection
class HelloFactory()
{
@Autowired
private Helloer helloer;
public HelloFactory()
{
}
public sayHello()
{
helloer.sayHello();
}
}
Field Injection is the the injection is occurred directly into the field. You might see that there's NO explicit way to inject the handler! Using Field Injection, the injection is occurred via the framework: the spring. This means that the code won't work without the framework, so SHOULD NOT be used.
댓글
댓글 쓰기