Spring/Spring

[Spring][Core] 2-2. Bean: Instantiating Beans

noahkim_ 2023. 10. 14. 17:27

1. Instantiating Beans

Instantiation with a Constructor

  • 빈을 생성하는 가장 일반적인 방법은 컨테이너가 빈의 클래스를 직접 인스턴스화하는 것입니다.
  • 이것은 자바에서 new 연산자를 사용하여 객체를 생성하는 것과 유사합니다.
  • XML 기반 : <bean/> 요소의 class 속성을 통해 이를 지정합니다.
<bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

 

Nested class names

  • 중첩 클래스(nested class)는 한 클래스 내부에 정의된 또 다른 클래스입니다.
  • 중첩 클래스를 빈으로 정의하려면 $ 표시를 사용하여 중첩클래스를 표현합니다. (fully qualified name)
<bean id="otherThingBean" class="com.example.SomeThing$OtherThing">
    <!-- bean configurations -->
</bean>

 

Instantiation with a Static Factory Method

  • 컨테이너가 정적 팩토리 메서드를 호출하여 빈을 생성하는 것입니다.
  • 이 방법은 빈을 생성하는 데 있어 추가적인 로직이 필요할 때 유용합니다.

 

public class ClientService {
    private static ClientService clientService = new ClientService();
    private ClientService() {}

    public static ClientService createInstance() {
        return clientService;
    }
}
<bean id="clientService" class="examples.ClientService" factory-method="createInstance"/>
  • 해당 팩토리 메서드가 위치한 클래스의 이름을 <bean/> 요소의 class 속성에 지정하면 됩니다.

 

Instantiation by Using an Instance Factory Method

  • 이미 컨테이너에 존재하는 또 다른 빈의 메서드를 호출하여 새로운 빈 객체를 생성하는 방법입니다.
  • 정적 메서드가 아닙니다.

 

public class DefaultServiceLocator {
    private static ClientService clientService = new ClientServiceImpl();

    public ClientService createClientServiceInstance() {
        return clientService;
    }
}
<bean id="serviceLocator" class="examples.DefaultServiceLocator">
	<!-- inject any dependencies required by this locator bean -->
</bean>

<bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>
  • class 속성을 비워 둡니다.
  • factory-bean : 인스턴스 팩토리 메서드를 포함하는 빈의 이름을 지정합니다.
  • factory-method : 호출할 메서드의 이름을 지정합니다.

  

Determining a Bean’s Runtime Type

  • 스프링 컨테이너에서 빈을 정의할 때 제공되는 클래스나 메타데이터는 단순히 초기 클래스 참조일 뿐입니다.
  • 초기 클래스 참조는 다양한 방식으로 실제 런타임에서의 빈의 타입을 결정할 수 있습니다.

 

팩토리 메서드 또는 FactoryBean
  • 빈의 정의에 선언된 팩토리 메서드나 FactoryBean을 사용하여 실제 런타임에서 빈의 타입이 달라질 수 있습니다.

 

인스턴스 수준의 팩토리 메서드
  • 경우에 따라 빈 메타데이터에서 클래스가 전혀 설정되지 않을 수도 있습니다.
  • 이 경우, factory-bean 이름을 통해 인스턴스 수준의 팩토리 메서드가 결정됩니다.

 

AOP 프록싱
  • AOP(Aspect-Oriented Programming)은 빈의 인스턴스를 프록시로 감쌀 수 있습니다.
  • 이렇게 되면, 프록시는 대상 빈의 실제 타입을 제한된 방식으로만 노출하게 됩니다.
    • 해당 빈이 구현한 인터페이스만 노출됩니다.

 

출처