본문 바로가기

springboot

static inner class를 spring에 bean으로 등록

김영한님의 스프링 핵심 원리 기초편을 듣다가 static에 대한 궁금증이 생겼다.

inner class인 TestConfig에서 static을 빼고 실행을 하니 "beans.factory.UnsatisfiedDependencyException" 이라는 에러가 뜨는데 static을 빼니 에러가 뜨면서 컨테이너 생성 및 bean 생성이 되지 않았다.

 

 

class StatefulServiceTest {

    @Test
    void statefulServiceSingleton(){
        ApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);
        StatefulService statefulService1 = ac.getBean(StatefulService.class);
        StatefulService statefulService2 = ac.getBean(StatefulService.class);

        //ThreadA : A사용자 10,000원 주문
        int userAPrice = statefulService1.order("userA", 10000);

        //ThreadA : B사용자 20,000원 주문
        int userBPrice = statefulService2.order("userB", 20000);

        //ThreadA : 사용자A가 주문금액을 조회함
        //int price = statefulService1.getPrice();
        System.out.println("price = " + userAPrice);

        //Assertions.assertThat(statefulService1.userAPrice()).isEqualTo(10000);
    }

    static class TestConfig{
        @Bean
        public StatefulService statefulService(){
            return new StatefulService();
        }
    }
}

 

 

마침 나의 궁금증에 대한 답변이 있어서 inner class, static inner class에 관련하여 자세히 알아보았다.

 

* inner class -> outer클래스의 인스턴스(객체)를 통해서만 접근이 가능
                   bean으로 등록 : X (inner class만 독립적으로 사용하지도 못하므로)

* static inner class -> outter객체 없이도 접근 가능
                  bean으로 등록 : O (단순히 outter클래스 통해서만 접근할 뿐이지 static클래스와 다를것이 없음)

 


결론

TestConfig클래스에 static를 뺀다면 outer클래스의 인스턴스를 통해서만 접근이 가능하므로, Test클래스가 생성되어야 TestConfig를 사용할 수 있다.

그러나 static를 뺀다면 Test클래스 내에는 TestConfig를 생성하기도 전에 스프링 컨테이너에서 TestConfig를 찾아오려고 하므로 스프링 빈에서는 그런 객체가 없다고 에러 메세지가 뜨는 것이다.

 

static를 붙이면 Test클래스와 별개로 TestConfig 클래스가 생성되고 빈으로 등록이 된다.

그러므로 Test클래스에서는 TestConfig를 불러와서 사용할 수 있다.

 


참고자료

1. TestConfig 클래스에서 static을 떼버리면.. - 인프런 | 질문 & 답변 (inflearn.com)

 

TestConfig 클래스에서 static을 떼버리면.. - 인프런 | 질문 & 답변

안녕하세요. 이번 수업때 임의로 쓰기 위해서 정의한  이너클래스인 TestConfig에서 static을 빼고 실행을 하니 'beans.factory.UnsatisfiedDependencyException'에러가 뜨면서 애초에 컨데이너 생성 및 bean 생성

www.inflearn.com

 

2. https://www.whiteship.me/static-inner-class-eb-a5-bc-spring-ec-97-90-bean-ec-9c-bc-eb-a1-9c--eb-93-b1-eb-a1-9d-ed-95-98-ea-b8-b0/

 

static inner class를 Spring에 bean으로 등록하기

public class Foo {    static class Bar {        static String say() {            return “Bar-Bar-Bar”;        }    }} 요런 클래스가 있습니다. static inner class는 일반 inner class완 다르게 outter 객체가 없이

www.whiteship.me

 

반응형

'springboot' 카테고리의 다른 글