728x90
@Configuration 이란?
Spring에는 여러가지 애노테이션(Annotation)이 있다.
이 중에 @Configuration은 설정파일 생성과 Bean 등록을 위한 애노테이션(Annotation)이다.
@Bean @Annotation 에 관한건 링크를 참조 : Bean Annotation
그럼 @Configuration은 어떤 역할을 할까?
@Configuration의 역할
@Configuration의 역할은 다음과 같다.
1. 내부에서 Bean을 등록할 때 각 Bean이 싱글톤(Singleton) 패턴을 유지할 수 있도록 해준다.
2. Spring Container가 Bean을 관리할 수 있게 한다.
예시 코드를 보자.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public MyClass init(){
System.out.println("test init");
return new MyClass(init());
}
@Bean
public MyClass function1(){
System.out.println("test function1");
return new Minus();
}
}
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
class MyTest {
@Test
void myTest(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(MyConfig.class);
MyConfig myConfig = ac.getBean(MyConfig.class);
System.out.println(myConfig);
}
}
위와 같은 코드로 테스트를 해보면 일단 getBean으로 추가 등록을 해줬기때문에, 총 3개의 출력이 나와야하지만,
2개의 출력이 나온다. 이유는, MyClass는 @Configuration으로. ac.getBean 또한 내부적으로 다음의 코드를 호출 하는데,
싱글톤인지 검사를 해서 추가한다. 따라서, 등록된 Bean은 하나로 처리되어 2개의 출력이 나온다.
# ac.getBean
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly)
MyClass에서 @Configuration 애노테이션을 제거하면 출력은 3개가 나온다.
'프레임워크 (Framework) > Spring' 카테고리의 다른 글
[CA] OpenSSL과 KeyTool을 통한 인증서 관리 및 mTLS (1) | 2024.11.15 |
---|