Spring/Spring

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

noahkim_ 2023. 10. 14. 17:27

0. Nested class names

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

 

 

1. Instantiating Beans

구분 설명 사용 용도
생성자 (기본 방식) 클래스의 생성자를 통해 객체를 직접 생성 가장 일반적인 방식, 단순한 객체 생성
정적 팩토리 메서드  static 메서드를 호출하여 객체 생성 생성에 커스텀 로직이 필요한 경우
인스턴스 팩토리 메서드 다른 빈의 인스턴스 메서드를 호출하여 객체 생성 팩토리 객체를 별도 관리할 필요가 있을 때

 

예제) 생성자

더보기
더보기
<bean id="exampleBean" class="examples.ExampleBean"/>
<bean name="anotherExample" class="examples.ExampleBeanTwo"/>

예제) 정적 팩토리 메서드 

더보기
더보기
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"/>

예제) 인스턴스 팩토리 메서드

더보기
더보기
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 : 호출할 메서드의 이름을 지정합니다.

 

  

2. Determining a Bean’s Runtime Type

  • 스프링 컨테이너에서 빈을 정의할 때 제공되는 클래스나 메타데이터는 단순히 초기 클래스 참조일 뿐입니다.
  • 다양한 방식으로 실제 런타임에서의 빈의 타입을 결정할 수 있습니다.
구분 설명 실제 타입 변화 가능성
팩토리 메서드  정적 또는 인스턴스 팩토리 메서드를 통해 객체를 생성 ✅ (메서드 반환 타입)
FactoryBean  FactoryBean<T> 인터페이스를 구현한 객체가 실제 빈을 생성 ✅ (getObject()의 반환 타입)
인스턴스 팩토리 메서드 다른 빈의 인스턴스 메서드를 호출해 객체 생성 (factory-bean의 메서드 반환 타입)
AOP 프록싱 AOP에 의해 빈이 프록시로 감싸져 있음
실제 타입이 프록시 타입으로 대체됨
✅ (프록시는 빈의 인터페이스만 노출함)

 

 

출처

'Spring > Spring' 카테고리의 다른 글

[Spring][Core] 2-5. Bean: Dependency Injection  (0) 2023.10.14
[Spring][Core] 2-4. Bean: Scopes  (0) 2023.10.14
[Spring][Core] 2-2. Bean: Naming  (0) 2023.10.14
[Spring][Core] 2-1. Bean: Definition  (1) 2023.10.14
[Spring][Core] 1. IoC Container  (0) 2023.10.14