Spring Boot @Configuration 어노테이션을 활용한 자바 기반 빈 설정 가이드

스프링 프레임워크의 초기 버전에서는 XML 파일을 통해 빈(Bean)을 등록하고 관리했습니다. 하지만 스프링 부트(Spring Boot)로 넘어오면서 @Configuration@Bean 어노테이션을 활용한 자바 기반 설정(Java-based Configuration)이 표준으로 자리 잡았습니다. 이 방식은 XML의 번거로움을 줄이고 타입 안정성을 제공하며, 리팩토링을 용이하게 만듭니다.

기존 XML 기반 빈 등록 방식

전통적인 스프링 환경에서는 beans.xml과 같은 XML 설정 파일을 사용하여 객체를 생성하고 의존성을 주입했습니다.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="member01" class="com.example.model.Member">
        <property name="name" value="kim"/>
        <property name="age" value="25"/>
    </bean>

    <bean id="cat01" class="com.example.model.Cat">
        <property name="name" value="nabi"/>
    </bean>

</beans>

이후 ApplicationContext를 통해 XML 파일을 로드하고 빈을 가져옵니다.

public class XmlApplication {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Member member = (Member) context.getBean("member01");
        System.out.println("Member Name: " + member.getName());
    }
}

@Configuration을 활용한 자바 기반 빈 등록

스프링 부트에서는 @Configuration 어노테이션이 부착된 클래스가 XML 설정 파일의 역할을 대신합니다. 해당 클래스 내부의 @Bean 어노테이션이 부착된 메서드는 각각의 <bean> 태그에 대응되며, 메서드의 이름이 빈의 ID로 사용됩니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public Member defaultMember() {
        return new Member("kim", 25);
    }

    @Bean
    public Cat defaultCat() {
        return new Cat("nabi");
    }
}

이제 스프링 부트의 메인 애플리케이션 클래스에서 ConfigurableApplicationContext를 사용하여 등록된 빈을 조회할 수 있습니다.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);

        Member member = context.getBean("defaultMember", Member.class);
        System.out.println("Member Name: " + member.getName());

        Cat cat = context.getBean("defaultCat", Cat.class);
        System.out.println("Cat Name: " + cat.getName());
    }
}

실행 결과 확인

애플리케이션을 실행하면 스프링 부트의 배너와 함께 내장 톰캣 서버가 시작되며, 컨텍스트에 등록된 빈의 속성이 정상적으로 출력됩니다.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v3.1.0)

2023-10-25 10:00:00.123  INFO 12345 --- [           main] com.example.DemoApplication              : Started DemoApplication in 2.5 seconds (process running for 3.1)
Member Name: kim
Cat Name: nabi

태그: SpringBoot configuration bean JavaConfig SpringFramework

9월 23일 08:37에 게시됨