빈 등록
Bean을 생성하기 위해서는 컴포넌트 정보와, 어떻게 bean으로 등록할지에 대한 정보를 담은 Configuration Metadata가 필요함. 여기서 어떤 scope로 등록할건지 등 설정해줌.
Bean의 종류
-> Singleton, Prototype, Request, Session 등
대표 Bean의 종류 설명
Singleton : 기본으로 다른 설정을 하지 않으면 bean은 singleton scope로 생성이 됨.
오직 하나의 인스턴스만 생성 된다는것.
* 방법
@Component 붙이기
@Component
public class StudentSingle {
}
그리고 사용하는데서는 @Autowired 사용하면 됨
Prototype
프로토타입은 빈을 받아올때마다 새로운 인스턴스를 생성
싱글톤 말고는 @Component 외에도 @Scope("prototype") 처럼 입력해주면 됨.
@Component @Scope("prototype")
public class StudentProto {
}
그다음 위의 각각 두 클래스를 실제 사용해보고 비교해 보자.
@Component
public class StudentRunner implements ApplicationRunner {
@Autowired
StudentSingle studentSingle1;
@Autowired
StudentSingle studentSingle2;
@Autowired
StudentProto studentProto1;
@Autowired
StudentProto studentProto2;
@Override
public void run(ApplicationArguments args){
System.out.println(studentSingle1);
System.out.println(studentSingle2);
System.out.println(studentProto1);
System.out.println(studentProto2);
}
}
결과
이렇듯 Singleton bean (StudentSingle)은 하나의 인스턴스고
Prototype bean (StudentProto) 은 인스턴스가 다르다.
이런식으로 Bean을 생성하고 사용할수 있겠다.
'Spring' 카테고리의 다른 글
[Spring] 02. Container 생성방법 (1) | 2024.01.28 |
---|---|
[Spring] 01. 기본개념 : IOC / DI / DI Container / Bean (2) | 2024.01.24 |