Bean Overview

2024. 6. 11. 15:21Spring Framework/Spring IoC

📌 Bean Overview

🔹 Spring IoC 컨테이너와 Bean

Spring IoC 컨테이너는 한개 이상의 Bean을 관리하며,
Bean은 구성 메타데이터(Configuration Metadata) 를 기반으로 생성됩니다.

💡 Spring에서 Bean은 IoC 컨테이너가 생성, 조립 및 관리하는 객체를 의미합니다.

➡️ Bean 정의는 내부적으로 BeanDefinition 객체로 변환되며, 다음과 같은 메타데이터를 포함합니다.

 

📍 BeanDefinition이 포함하는 주요 정보

클래스 이름 → Bean의 실제 구현 클래스
동작 설정 → Scope, 라이프사이클 콜백 등
의존성 → 다른 Bean에 대한 참조 (Dependency)
기타 설정 → 커넥션 풀 크기, 캐시 설정 등

💡 Bean 정의를 통해 Spring 컨테이너는 객체를 효율적으로 생성하고 조립할 수 있습니다.

 

🔹 BeanDefinition의 주요 속성

속성 설명
class Bean을 생성할 클래스 지정
name Bean의 식별자 (id, name 속성 활용)
scope Bean의 범위 (싱글톤, 프로토타입 등)
constructor arguments 생성자 주입 시 필요한 값
properties Setter 주입 시 필요한 값
autowiring mode 자동 의존성 주입 방식 (@Autowired 등)
lazy initialization Bean의 지연 로딩 여부 설정
initialization method 초기화 시 실행할 메서드 지정
destruction method 소멸 시 실행할 메서드 지정

💡 Spring 컨테이너는 BeanDefinition을 통해 객체를 조립하고 의존성을 주입합니다.

 

🔹 Bean 등록 방식

Spring에서는 Bean을 등록하는 다양한 방법이 존재합니다.

📍 1️⃣ XML 기반 Bean 정의

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

➡️ XML을 사용하여 <bean> 엘리먼트로 정의

 

📍 2️⃣ Java 기반 Bean 정의 (추천)

@Configuration
public class AppConfig {
    @Bean
    public ExampleBean exampleBean() {
        return new ExampleBean();
    }
}

➡️ @Configuration@Bean을 활용한 Java 기반 구성

 

📍 3️⃣ Groovy 기반 Bean 정의

beans {
    exampleBean(ExampleBean) {}
}

➡️ Groovy DSL을 사용하여 Bean 정의 가능

 

🔹 Bean의 식별자(Naming) 및 별칭(Aliasing)

Bean은 컨테이너 내에서 하나 이상의 고유한 이름을 가질 수 있습니다.
id 속성 → 단일 식별자 지정
name 속성 → 여러 개의 별칭(alias) 지정 가능

<bean id="myBean" class="com.example.MyBean" name="beanAlias1, beanAlias2"/>

➡️ id="myBean" 으로 기본 이름을 설정하고, name="beanAlias1, beanAlias2" 를 통해 별칭 제공

 

📍 별칭만 추가하는 방법 (<alias/> 활용)

<alias name="myBean" alias="anotherName"/>

➡️ myBeananotherName으로도 사용할 수 있도록 설정

 

🔹 Bean 인스턴스화 방법 (객체 생성 방식)

Spring에서는 다양한 방식으로 Bean을 생성할 수 있습니다.

📍 1️⃣ 디폴트 생성자(Constructor) 사용

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

➡️ new ExampleBean() 방식으로 객체 생성

💡 디폴트 생성자가 필요하며, 별도의 설정이 없어도 사용 가능

 

📍 2️⃣ 정적 팩토리 메서드(Static Factory Method) 사용

<bean id="clientService"
    class="examples.ClientService"
    factory-method="createInstance"/>

 

➡️ ClientService.createInstance() 정적 메서드를 호출하여 Bean 생성

public class ClientService {
    private static final ClientService instance = new ClientService();

    private ClientService() {}

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

➡️ Singleton 패턴을 적용한 팩토리 메서드를 활용 가능

 

📍 3️⃣ 인스턴스 팩토리 메서드(Instance Factory Method) 사용

<bean id="serviceLocator" class="examples.DefaultServiceLocator"/>
<bean id="clientService"
    factory-bean="serviceLocator"
    factory-method="createClientServiceInstance"/>

➡️ 기존 Bean을 활용하여 새로운 Bean을 생성하는 방식

public class DefaultServiceLocator {

	private static ClientService clientService = new ClientServiceImpl();

	private static AccountService accountService = new AccountServiceImpl();

	public ClientService createClientServiceInstance() {
		return clientService;
	}

	public AccountService createAccountServiceInstance() {
		return accountService;
	}
}

➡️ DefaultServiceLocatorcreateClientServiceInstance() 호출하여 Bean 생성

 

🔹 Bean 오버라이딩(Overriding) 방지 설정

Spring에서는 동일한 ID를 가진 Bean이 중복될 경우 오버라이딩이 발생할 수 있습니다.
이러한 동작을 방지하려면 allowBeanDefinitionOverriding 속성을 false로 설정합니다.

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setProperty("spring.main.allow-bean-definition-overriding", "false");
context.refresh();

➡️ Bean 중복 등록 시 예외 발생 (BeanDefinitionOverrideException)

 

💡 Spring Boot 환경에서는 application.properties에서 설정 가능

spring.main.allow-bean-definition-overriding=false

 

🔹 Bean의 런타임 타입 확인

Bean의 실제 타입은 BeanFactory.getType() 메서드를 활용하여 확인할 수 있습니다.

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Class<?> beanType = context.getType("myBean");
System.out.println("Bean Type: " + beanType.getName());

➡️ Bean의 실제 타입을 가져올 수 있음

 

🔹 Spring Bean 정리 📝

Spring IoC 컨테이너는 BeanDefinition을 활용하여 객체를 생성하고 관리
Bean의 주요 속성 → class, name, scope, lifecycle 등
Bean 등록 방식
 ✅ XML (<bean> 태그 활용)
 ✅ Java (@Configuration + @Bean 활용)
 ✅ Groovy (beans {} 블록 활용)
Bean 인스턴스화 방법
 ✅ 디폴트 생성자 사용
 ✅ 정적 팩토리 메서드 사용
 ✅ 인스턴스 팩토리 메서드 사용
Bean 오버라이딩 방지 가능 (allowBeanDefinitionOverriding=false)
Bean의 런타임 타입은 getType()으로 확인 가능

 

💡 Spring Boot에서는 대부분 Java 기반 구성을 활용하는 것이 일반적이며, @Bean을 이용해 직관적으로 관리할 수 있습니다! 🚀

 

출처 : https://docs.spring.io/spring-framework/reference/core/beans/definition.html

 

Bean Overview :: Spring Framework

Every bean has one or more identifiers. These identifiers must be unique within the container that hosts the bean. A bean usually has only one identifier. However, if it requires more than one, the extra ones can be considered aliases. In XML-based configu

docs.spring.io

 

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

Dependencies  (0) 2024.11.14
Dependency Injection  (0) 2024.06.11
Using @Autowired  (0) 2023.12.10
Dependencies and Configuration in Detail  (0) 2023.12.10
Introduction to the Spring IoC Container and Beans  (0) 2023.12.10