본문으로 바로가기

Spring (AI)

BeanPostProcessor와 FactoryBean — 객체 생성 전후의 확장 지점과 팩토리 객체의 차이

L.logit 2026. 11. 23.

1. 왜 BeanPostProcessor와 FactoryBean이 필요한가?

앞 편에서는 Bean 생성·초기화·소멸과 BeanPostProcessor가 개입하는 지점을 살펴보았다. 이번에는 그 확장 지점을 직접 구현하는 방법과, 일반 객체 대신 팩토리 객체를 등록하여 제품 객체를 노출하는 FactoryBean 계약을 비교한다.

BeanPostProcessor는 생성된 Bean 인스턴스에 개입하는 확장 지점이고, FactoryBean은 BeanFactory가 조회자에게 노출할 객체를 만들어 주는 팩토리 계약이다.

두 인터페이스는 이름이 비슷하지만 객체를 다루는 시점과 목적이 다르다.

1.1 역사와 설계 배경

Spring은 XML 설정 중심의 초기 시절부터 컨테이너를 상속·수정하지 않고도 사용자 정의 초기화 처리, 프록시 적용, 복잡한 객체 생성에 대응할 수 있도록 확장 인터페이스를 제공해 왔다. BeanPostProcessor와 FactoryBean은 Spring 2.x 이전부터 존재한 오래된 핵심 계약이다. 현재의 어노테이션 처리와 AOP 자동 프록시도 이러한 컨테이너 확장 철학 위에서 이해할 수 있다.

일반적인 생성자 또는 @Bean 팩토리 메서드로 해결할 수 있는 생성 작업에 FactoryBean을 무조건 도입할 필요는 없다. 인프라 객체의 노출 방식과 생성 정책을 BeanFactory 계약에 통합할 필요가 있을 때 유용하다.

2. BeanPostProcessor의 계약과 실행 시점

2.1 두 가지 핵심 콜백

BeanPostProcessor의 기본 계약은 postProcessBeforeInitialization(Object bean, String beanName)과 postProcessAfterInitialization(Object bean, String beanName)이다. 일반적인 Bean 생성 경로에서는 의존성 주입 이후, 초기화 콜백 직전과 직후에 호출된다. 반환 객체는 원본 Bean일 수도 있고 래핑된 객체일 수도 있다.

public interface BeanPostProcessor {
    default Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException { return bean; }
    default Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException { return bean; }
}

위 코드는 인터페이스의 핵심 시그니처를 설명하기 위한 축약 표현이다. 실제 API는 @Nullable 등의 부가 선언 및 문서 계약을 포함한다.

2.2 일반적인 초기화 순서

  • 인스턴스 생성과 의존성 설정이 먼저 수행된다.
  • BeanNameAware, BeanFactoryAware 등 일부 Aware 콜백은 초기화 전 후처리보다 앞선다.
  • postProcessBeforeInitialization() 실행. CommonAnnotationBeanPostProcessor를 통한 @PostConstruct 처리는 이 구간에 포함된다.
  • InitializingBean.afterPropertiesSet() 및 지정된 custom init-method 실행.
  • postProcessAfterInitialization() 실행. 이 단계에서 프록시로 교체할 수 있다.

이는 일반적인 singleton Bean의 대표 경로이다. InstantiationAwareBeanPostProcessor의 생성 전 단축 경로, 순환 참조의 조기 노출, FactoryBean 제품 객체의 후처리는 별도로 이해해야 한다.

2.3 BeanFactoryPostProcessor와 혼동하지 않기

구분 BeanFactoryPostProcessor BeanPostProcessor
대상 BeanDefinition 등 설정 메타데이터 생성된 Bean 인스턴스
대표 시점 일반 Bean 인스턴스 생성 전 Bean 초기화 전후
목적 설정 값 수정, 정의 추가 등 초기화 처리, 객체 래핑 및 프록시
예시 PropertySourcesPlaceholderConfigurer AutowiredAnnotationBeanPostProcessor, 자동 프록시 생성기

BeanFactoryPostProcessor 안에서 getBean()을 호출해 일반 Bean을 조기 생성하면 정상적인 후처리기 등록 순서를 깨뜨릴 수 있다. 두 확장 지점의 대상이 다르다는 점이 핵심이다.

3. BeanPostProcessor의 등록과 적용 범위

3.1 ApplicationContext의 자동 감지

ApplicationContext는 BeanPostProcessor 타입의 Bean을 조기에 찾아 등록한다. 이때 BeanPostProcessor 자신과 그 생성에 직접 필요한 Bean은 모든 후처리기의 적용을 받지 못할 수 있다. 특히 자동 프록시 대상에서 제외되는 상황이 발생할 수 있다.

BeanPostProcessor를 @Bean으로 정의한다면 반환 타입을 BeanPostProcessor 또는 구체 구현 타입으로 명확히 선언하고, 가능하면 static @Bean 메서드를 사용해 구성 클래스의 불필요한 조기 인스턴스화를 줄이는 것이 권장된다.

3.2 순서와 컨테이너 경계

자동 감지된 여러 BeanPostProcessor는 PriorityOrdered, Ordered 등의 정렬 규칙에 따라 등록될 수 있다. 반면 addBeanPostProcessor()로 직접 등록한 경우에는 등록 순서가 우선하며 Ordered 값에 의한 재정렬을 기대하면 안 된다. 부모·자식 컨테이너에서는 각 BeanPostProcessor가 자신이 등록된 컨테이너의 Bean에 적용된다는 점도 중요하다.

4. FactoryBean은 무엇을 반환하는가?

4.1 팩토리 Bean과 제품 객체의 구분

FactoryBean<T>는 getObject(), getObjectType(), isSingleton()으로 제품 객체를 노출하는 계약이다. 예를 들어 paymentGateway라는 이름에 FactoryBean 구현체를 등록하면, getBean("paymentGateway")는 일반적으로 FactoryBean 자체가 아닌 getObject()의 결과를 반환한다.

getBean("paymentGateway")는 제품 객체를, getBean("&paymentGateway")는 FactoryBean 구현체를 조회한다.

여기서 &는 Bean 이름의 역참조 접두사이며, HTML에서는 &amp;로 이스케이프되어 표시된다.

4.2 FactoryBean 자체의 Scope와 제품의 캐시 정책

FactoryBean 구현체의 Bean scope와 FactoryBean.isSingleton()이 나타내는 제품 객체의 공유 정책은 별개의 축이다. 일반적인 singleton FactoryBean이 isSingleton()을 true로 반환하면 BeanFactory가 제품 객체를 캐시할 수 있다. false는 캐시하지 않는다는 의미에 가깝고, 반드시 매번 독립적인 인스턴스를 반환한다는 보증은 아니다.

getObjectType()은 제품의 타입을 미리 알 수 있게 하는 중요한 계약이다. 타입 탐색과 자동 주입에 영향을 주므로 가능하면 초기화 전에도 안전하게 타입을 반환해야 한다. getObject() 호출이 초기 부트스트랩 중 발생할 수 있다는 점 역시 주의해야 한다.

5. 내부 구현 경로와 생명주기 경계

5.1 BeanPostProcessor의 초기화 경로

AbstractAutowireCapableBeanFactory의 대표적인 initializeBean() 경로는 Aware 처리, applyBeanPostProcessorsBeforeInitialization(), invokeInitMethods(), applyBeanPostProcessorsAfterInitialization()을 이어 간다. 각 단계는 실제 Bean 인스턴스를 대상으로 하며, 초기화 후 후처리기가 원본과 다른 객체를 반환하면 이후 조회자는 래핑 객체를 받을 수 있다.

5.2 FactoryBean의 제품 노출 경로

AbstractBeanFactory의 doGetBean() 경로에서는 일반 Bean 인스턴스를 확보한 다음 getObjectForBeanInstance()를 통해 FactoryBean 여부를 구분한다. FactoryBean 제품의 조회·캐시는 FactoryBeanRegistrySupport의 getObjectFromFactoryBean() 및 관련 캐시 메커니즘과 연결된다. singleton 제품에는 제품 객체 후처리가 적용될 수 있지만, 이 경로를 일반 Bean 생성 시의 전체 생명주기와 동일시해서는 안 된다.

특히 FactoryBean 인터페이스 문서는 컨테이너가 FactoryBean 자체의 생명주기를 관리하며, 제품 객체의 소멸 콜백까지 자동으로 보장하지는 않는다고 명시한다. 제품이 별도 자원을 소유한다면 FactoryBean의 DisposableBean 구현 등으로 명시적으로 정리해야 한다.

5.3 FactoryBean과 @Bean 메서드는 다르다

항목 FactoryBean<T> @Bean 팩토리 메서드
계약 FactoryBean 구현 객체가 제품을 노출 @Configuration 등의 메서드가 Bean을 정의
일반 이름 조회 FactoryBean의 제품을 노출 메서드에서 생성한 Bean을 조회
& 접두사 FactoryBean 자체를 조회 일반적인 @Bean에는 해당하지 않음
주요 사용처 프레임워크·인프라 팩토리 계약 애플리케이션 설정과 외부 객체 등록

6. Java 예제로 관찰하는 후처리와 팩토리

6.1 BeanPostProcessor 예제

아래 코드는 Spring Framework 6.2 계열과 Java 17 이상을 전제로 하며, spring-context 의존성을 사용한다. 파일별 public 타입은 실제 Java 프로젝트에서 별도 파일로 분리한다.

package example;

import org.springframework.beans.factory.config.BeanPostProcessor;

public class AuditPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String name) {
        if ("paymentService".equals(name)) System.out.println("before:" + name);
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String name) {
        if ("paymentService".equals(name)) System.out.println("after:" + name);
        return bean;
    }
}
package example;

import org.springframework.beans.factory.InitializingBean;

public class PaymentService implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        System.out.println("init:paymentService");
    }
}
package example;

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

@Configuration(proxyBeanMethods = false)
public class AppConfig {
    @Bean
    public static AuditPostProcessor auditPostProcessor() {
        return new AuditPostProcessor();
    }
    @Bean
    public PaymentService paymentService() {
        return new PaymentService();
    }
}
package example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
            context.getBean(PaymentService.class);
        }
    }
}

paymentService에 대해 관찰하려는 순서는 before:paymentService → init:paymentService → after:paymentService이다. 실제 출력에는 컨테이너가 생성하는 다른 Bean에 대한 처리 여부와 로그가 별도로 관여할 수 있으므로 예제는 해당 Bean 이름만 필터링한다.

6.2 FactoryBean 예제

package example;

public interface PaymentGateway {
    String provider();
}
package example;

public class FakePaymentGateway implements PaymentGateway {
    @Override
    public String provider() { return "FAKE"; }
}
package example;

import org.springframework.beans.factory.FactoryBean;

public class PaymentGatewayFactoryBean implements FactoryBean<PaymentGateway> {
    @Override
    public PaymentGateway getObject() {
        return new FakePaymentGateway();
    }
    @Override
    public Class<?> getObjectType() {
        return PaymentGateway.class;
    }
    @Override
    public boolean isSingleton() {
        return true;
    }
}
package example;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class FactoryMain {
    public static void main(String[] args) {
        try (var context = new AnnotationConfigApplicationContext()) {
            context.registerBean("gateway", PaymentGatewayFactoryBean.class);
            context.refresh();
            PaymentGateway product = context.getBean("gateway", PaymentGateway.class);
            Object factory = context.getBean("&gateway");
            System.out.println(product.provider());
            System.out.println(factory instanceof PaymentGatewayFactoryBean);
            System.out.println(product == context.getBean("gateway"));
        }
    }
}

예상되는 세 줄은 FAKE, true, true이다. 마지막 true는 singleton 제품 객체 캐시 정책을 보여준다. 예제의 getObject()는 새 객체를 생성하지만 제품 조회는 캐시된 객체를 돌려줄 수 있다.

7. 장단점과 적용 판단

관점 BeanPostProcessor FactoryBean
장점 여러 Bean에 공통 처리·프록시 적용 복잡한 제품 객체 생성·노출을 컨테이너와 통합
주의점 순서·조기 생성·예상치 못한 래핑 팩토리와 제품의 생명주기·타입·캐시 구분 필요
권장 상황 프레임워크 수준의 횡단 관심 처리 특수 인프라 객체를 팩토리 계약으로 제공
대안 직접 초기화 콜백, 명시적 데코레이터 일반 생성자, @Bean 메서드

애플리케이션의 단순 결제 처리 객체를 생성하는 데는 일반 생성자 주입과 @Bean이 대개 더 명료하다. 반면 여러 Bean의 공통 계측, 인프라 프록시 생성, 타입이 동적으로 결정되는 제품 노출처럼 컨테이너 수준의 확장이 필요할 때 두 인터페이스의 가치가 드러난다.

8. 자주 발생하는 오해와 교정

오해 정확한 설명
BeanPostProcessor가 BeanDefinition을 수정한다 BeanDefinition 수정의 대표 확장 지점은 BeanFactoryPostProcessor다.
모든 BeanPostProcessor는 초기화 이후에만 동작한다 표준 계약에는 초기화 전후 두 콜백이 있다. 관련 하위 인터페이스는 생성 전후에도 개입한다.
FactoryBean은 BeanFactory와 같다 FactoryBean은 특정 제품 객체를 노출하는 사용자 구현 계약이고, BeanFactory는 컨테이너의 Bean 조회·관리 계약이다.
FactoryBean.isSingleton()은 팩토리 자신의 scope다 제품 객체의 공유·캐시 정책이며 팩토리 자신의 Bean scope와 별개다.
FactoryBean의 제품은 일반 Bean과 동일한 소멸 콜백을 자동 보장받는다 FactoryBean 제품 객체의 소멸은 별도 관리가 필요할 수 있다.
@Bean과 FactoryBean은 같은 기능이다 @Bean은 Bean 정의 방식, FactoryBean은 제품 객체 노출을 위한 인터페이스다.

9. 핵심 정리와 다음 학습 질문

BeanPostProcessor는 Bean 인스턴스의 초기화 전후를 확장하고, FactoryBean은 BeanFactory가 제품 객체를 노출하는 방식을 확장한다. 두 인터페이스의 차이는 처리 시점보다도 관리 대상과 계약의 차이에서 분명해진다.

BeanDefinition, 생성, 주입, 초기화, 프록시, 조회 결과를 한 줄의 실행 과정으로만 암기하면 FactoryBean 제품과 일반 Bean의 생명주기 차이를 놓치기 쉽다. 다음 편에서는 이러한 후처리 확장이 Spring AOP의 프록시 생성으로 연결되는 과정을 살펴본다.

  • BeanPostProcessor와 BeanFactoryPostProcessor는 각각 무엇을 변경하는가?
  • postProcessAfterInitialization()이 원본 대신 프록시를 반환하면 Bean 조회 결과는 어떻게 달라지는가?
  • FactoryBean의 isSingleton()과 팩토리 자신의 singleton scope는 왜 별개인가?
  • FactoryBean이 만든 제품 객체의 종료 자원은 누가 정리해야 하는가?
  • AOP의 자동 프록시 생성기는 어떤 후처리 확장 지점을 사용하는가?

다음 편: Spring AOP — Proxy와 관심사 분리

10. 참고 문헌 및 공식 자료