Framework/Spring

[Spring] 스프링의 Bean을 어떻게 쓸 수 있을까?

KOOCCI 2022. 7. 23. 16:45

목표 : Spring 의 Bean을 간단히 사용해볼 수 있다.


  1. 스프링은 무엇을 도와주는가?
  2. 스프링의 사용법은 어떻게 되는가?

라는 두가지 주제 중, 스프링은 무엇을 도와주는가? 에 대해  간략히 정의와 함께 알아보았고,

스프링의 사용법을 알기 이전에 그 사용 용어들부터 정리해보고 있다.

 

우선, 이전 포스트에서 Spring 의 IoC Container가 무엇인지 설명할 수 있게 되었다.

다만, 그 Detail을 조금 더 파고 들고자 한다.

 

Bean이라는 것

앞서 보던 Spring 공식 문서에서 Bean Overview를 통해 자세히 알아보고자 한다.

사실 우린 Bean이라는 것도 이미 배웠다. 

Bean Spring Container (ApplicationContext 구현체) 가 관리하고 생성하고 인스턴스화 해주는 객체다.

그리고 공식 문서의 첫 문장은 IoC Container가 하는 일에 대해 적혀있다..

A Spring IoC container manages one or more beans. These beans are created with the configuration metadata that you supply to the container (for example, in the form of XML <bean/> definitions).

 

Spring IoC container 는 다수의 Bean들을 관리한다. 이 Bean들은 Configuration Metadata를 통해 만들어지며, 이는 XML과 같은 형태로 제공된다.

 

그럼 이제 Bean이라는 게 어떻게 정의되는지 알아보도록 하자.

 

Bean은 어떻게 생성할 수 있는가?

Annotation은 차츰 진행하면서 다시한번 공부하기로 하고, XML 형태를 먼저 보도록 하자.

XML의 <bean/>으로 정의되는  Bean은 여러가지 Property들이 있다.

용도에 따라 각기 다른 내용들이 있는데, 우선은 Class, Name 두가지에 집중해서 볼 예정이다.

Naming Beans

bean은 하나 이상의 Unique한 ID를 갖는다.

XML에서는 id나 name attribute로 설정가능하다. (ID는 유일하지만, name은 여러개 작성이 가능하다)

유니크한 값이 있는 이유는 같은 Class라도 Spring이 관리하는 Bean이 다를 수 있기 때문이다.

<bean id="dao1" name="dao2, dao3" class="com.test.myobj"/>
<bean id="new_dao"  class="com.test.myobj"/>

 

Instantiating Beans

Bean을 객체로 만드는 건 크게 3가지 방법이 있다.

  1. Constructor (생성자)
  2. Static Factory Method
  3. Instance Factory Method

하기 예시로 설명해보자.

<bean id="exampleBean" class="examples.ExampleBean"/>

<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

먼저 bean의 class를 정의하면, ExampleBean의 기본 생성자를 통해 Bean을 만든다.

만약, 기본 생성자가 없다면? 그럼 에러가 나고 별도 과정이 더 필요하다.

 

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>
public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}

factory-method라는 attribute를 추가하였고,  Static Factory Method로 생성하는 방법이다.

<!-- the factory bean, which contains a method called createInstance() -->
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
    <!-- inject any dependencies required by this locator bean -->
</bean>

<!-- the bean to be created via the factory bean -->
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

마지막으로 Instance Factory Method이다.

이 때는 2개의 bean이 필요하다.

  1. Bean을 만들어줄 클래스가 정의된 Bean
  2. 사용할 Bean (class 대신 factory-bean이 들어간다.)

사용할 Bean에 factory-bean이라는 attribute로 Bean을 만들어줄 클래스가 정의된 Bean을 지정하고, 동작시킬 factory-method를 정의해준다.

 

자기 자신이 Factory-method를 가진 경우 앞선 static factory method를 사용하고, 외부에서 자신을 정의시켜준다면, instance factory method를 사용한다.

public class DefaultServiceLocator {

    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}

Wrap up

 Configuration Metadata를 통해 간단한 Bean을 만드는 법을 알 수 있었다.

 

아무래도 Bean에 대해 시원하게 다루지 못한 감이 있다.

DI라는 개념과 함께 Bean Scope, Annotation으로 발전시켜나가야 하는데, 모든 걸 한번에 다룰 수 없으니

다시한번 Wrap up하는 시점이 나오지 않을까 한다.