Bean Scope

이한주·2023년 4월 19일
0

스프링 공식문서에서 총 6개의 빈 스코프를 볼 수 있다.

기본적으로 싱글톤 스코프를 가진다.

다음과 같이 같은 빈에 대해서 equal 비교를 했을 때 true 결과를 볼 수 있다.

var voucherRepository =
    BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(), VoucherRepository.class, "memory");
var voucherRepository2 =
		BeanFactoryAnnotationUtils.qualifiedBeanOfType(applicationContext.getBeanFactory(), VoucherRepository.class, "memory");

System.out.println(MessageFormat.format("voucherRepository {0}", voucherRepository));
System.out.println(MessageFormat.format("voucherRepository2 {0}", voucherRepository2));
System.out.println(voucherRepository == voucherRepository2);

스코프를 임의로 변경할 수 있는데 @Scope 어노테이션을 이용해 바꿀 수 있다.

아래와 같이 빈 클래스 파일에서 PROTOTYPE 스코프로 바꿀 수 있다.

@Qualifier("memory")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Repository
public class MemoryVoucherRepository implements VoucherRepository {

    private final Map<UUID, Voucher> storage = new ConcurrentHashMap<>();

    @Override
    public Optional<Voucher> findById(UUID voucherId) {
        return Optional.ofNullable(storage.get(voucherId));
    }

    @Override
    public Voucher insert(Voucher voucher) {
        storage.put(voucher.getVoucherId(), voucher);
        return voucher;
    }
}

스코프를 변경 후 equal 비교를 했을 때 다른 객체임을 확인할 수 있다.

코드

https://github.com/yanJuicy/kdt-spring-order/tree/648acdf70e94b0fa69a51343c26b3b902eb30f30

0개의 댓글