개발/개발 구현

Java Spring – XML 기반 Bean 설정 정리

jineddy 2025. 4. 11. 09:48
728x90

최근 프로젝트에서 Spring 설정을 대부분 XML 기반으로 구성하는 케이스가 있었고, 이에 따라 자주 사용되는 Bean 설정 방식들을 정리해본다.

이 글은 XML 방식의 Spring 설정이 필요한 상황에서 참고용으로 사용하기 좋다.

 

1. 변수 없는 Bean 생성

가장 기본적인 형태의 Bean 선언으로, 단순히 클래스만 지정하면 된다.

<bean id="testService" class="com.example.test.TestService" />

 

2. property 태그를 이용한 Bean 의존성 주입 (Setter 방식)

Setter 메서드를 통해 값을 주입하는 방식이다.

<bean id="testService" class="com.example.test.TestService">
    <property name="param" value="value"/>
    <property name="repository" ref="testRepository"/>
</bean>

<bean id="testRepository" class="com.example.test.TestRepository" />
  • value : 문자열, 숫자 등 단순 값 주입
  • ref : 다른 Bean을 참조하여 주입

 

3. constructor-arg를 이용한 생성자 주입

생성자 인자를 이용해 값을 주입할 수 있다. 순서를 중요하게 고려해야 한다.

<bean id="testService" class="com.example.test.TestService">
    <constructor-arg value="value" />
    <constructor-arg>
        <ref bean="testRepository"/>
    </constructor-arg>
</bean>

<bean id="testRepository" class="com.example.test.TestRepository" />

 

4. factory-method를 이용한 정적 메서드 기반 Bean 생성

정적 메서드(static method)를 호출하여 Bean을 생성하는 방식이다.

<bean id="testFactoryService"
      class="com.example.test.TestFactoryService"
      factory-method="getInstance">
    <constructor-arg>
        <props>
            <prop key="param">value</prop>
        </props>
    </constructor-arg>
</bean>

 

※ 참고 및 주의사항

  • 위 4가지 방식은 Spring XML 설정에서 가장 핵심적인 Bean 설정 방식이다.
  • SI 프로젝트를 하다보면 레거시 시스템을 다루어야 할 경우가 있어서 해당 방법도 이해하면 많은 도움이 된다.
  • Spring Boot 이후로는 대부분 @Configuration, @Bean, @Component 등 Java Config 방식 또는 어노테이션 기반 설정이 일반적이다.

 

728x90