#WIL - 23.04.17~23.04.23

Jay Ji·2023년 4월 23일
0

WIL I write every week?

목록 보기
3/6
post-thumbnail

What I learned

I am going mainly discuss about IoC, DI and Bean in Spring framework.

What is IoC?

IoC(Inversion of Control) is a principle that involves transferring control of objects or parts of a program to a container or framework. This approach is commonly used in object-oriented programming.

Traditional programming involves custom code making calls to a library, whereas IoC allows a framework to control the program flow and make calls to custom code. To enable this, frameworks use abstractions with built-in additional behavior. If we want to add our own behavior, we can extend the framework's classes or use our own classes as plugins.

The benefits of this architecture include separating the execution of a task from its implementation, making it easier to switch between different implementations, increasing program modularity, facilitating testing by isolating components or mocking dependencies, and enabling components to communicate through contracts.

IoC can be implemented through various mechanisms, such as the Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).

What is DI?

DI(Dependency Injection) is a pattern that can be utilized to implement IoC. It involves inverting control by setting an object's dependencies.

Rather than objects setting up connections with other objects or injecting objects into one another, an assembler handles this task.

Here is an example of how we would create an object dependency in traditional programming:

public class Store {
    private Item item;
 
    public Store() {
        item = new ItemImpl1();    
    }
}

In the example, we have to instantiate an implemnatation of Item interface within Store class itself.

Using DI, we can rewrite the example without specifying the implementation of the Item that we want:

public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}

What is Spring IoC Container? (Feat. Bean)

A defining feature of frameworks that utilize IoC is the presence of an IoC container.

Within the Spring framework, the interface ApplicationContext serves as the IoC container. This container is responsible for creating, configuring, and organizing objects, also known as beans, as well as managing their lifecycles.

Spring offers various implementations of the ApplicationContext interface.

To create beans, the container uses configuration metadata, which can be in the form of XML configuration or annotations.

Dependency Injection can be achieved in Spring through constructors, setters, or fields.

profile
Think out of the Box

0개의 댓글