component scan에 관련해서
304
작성한 질문수 3
밑에 코드 중에
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);이 코드가 이해가 안되서 질문 드립니다. 강사님이 이렇게 코드를 작성하면 자동으로 component scan이 된다고 하셨는데, 밑에 ClientBean과 PrototypeBean은 @Component어노테이션이 없습니다. 따라서 @Autowired도 안되는거 아닌가요??
package hello.core.scope;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import static org.assertj.core.api.Assertions.assertThat;
public class SingletonWithPrototypeTest1 {
@Test
void singletonClientUsePrototype(){
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(ClientBean.class, PrototypeBean.class);
ClientBean clientBean1 = ac.getBean(ClientBean.class);
int count1 = clientBean1.logic();
assertThat(count1).isEqualTo(1);
ClientBean clientBean2 = ac.getBean(ClientBean.class);
int count2 = clientBean2.logic();
assertThat(count2).isEqualTo(2);
}
@Scope("singleton")
static class ClientBean{
private final PrototypeBean prototypeBean;
@Autowired
public ClientBean(PrototypeBean prototypeBean) {
this.prototypeBean = prototypeBean;
}
public int logic(){
prototypeBean.addCount();
return prototypeBean.getCount();
}
}
@Scope("prototype")
static class PrototypeBean {
private int count = 0;
public void addCount() {
count++;
}
public int getCount() {
return count;
}
@PostConstruct
public void init() {
System.out.println("PrototypeBean.init = " + this);
}
@PreDestroy
public void destroy() {
System.out.println("PrototypeBean.destroy");
}
}
}
답변 1
0
안녕하세요. 심재윤님, 공식 서포터즈 코즈위버입니다.
스프링 앱을 실행할 때 컴포넌트 스캔 과정을 거칩니다. 이 때 @Component 어노테이션이 붙은 객체(@Component 어노테이션을 구현하고 있는 하위 어노테이션 포함, @Controller, @Service, @Repository 등등)를 스프링빈으로 등록하고 스프링 빈은 @Autowired 를 통해 주입할 수 있습니다.
그리고 AnnotationConfigApplicationContext() 의 파라미터로 넘긴 객체들도 스프링 빈으로 등록하게 되고 이 객체들 또한 @Autowired 로 주입받을 수 있습니다.
감사합니다.
코드 자료
0
48
2
구현체가 동적으로 정해질 때, 팩토리 기법을 사용하나요?
0
55
2
MemberService의 인터페이스를 왜 사용하는지 궁금합니다.
0
76
1
롬복 @Setter를 써야 하는 상황이 있는건가요?
0
91
1
빈 등록 메서드의 파라미터가 빈이 아니어도 되나요?
0
81
1
테스트 속도가 나중에 영향이 있을까요?
0
77
1
gradle 설정 안떠서 질문 남깁니다!
0
121
2
build.gradle로 프로젝트를 여는 이유
0
86
1
provider 사용하는 이유
0
90
1
다음 강의 뭘 들어야 할까요
0
126
2
프로토타입 빈, 직접 destroy 호출 안 할 경우
0
66
1
beanB
0
82
2
퀴즈다시풀기
0
68
1
Gradle로 바꿔도 오류가 똑같이 발생하네요 ㅠㅠ
0
92
2
"중복 등록과 충돌" 강의에서 강사님과 다른 에러가 발생합니다.
0
67
3
run 실행했는데 결과창이 이렇게 뜨네요 왜 그런건가요>
0
106
2
도메인의 정의?
0
59
1
ApplicationContext 질문입니다.
0
63
1
@Scope의 proxyMode를 사용할때 단위 테스트 방법
0
89
2
ai api 선정하기 관련 질문
0
118
2
생성자 자동주입 관련해서
0
65
1
생성자 직접 호출 vs 팩토리 메서드 패턴
0
97
2
Spring에서 SessionScope와 RequestScope는 함께 사용되나요?
1
66
1
12:25
0
79
2





