WEB개발

[SPRING] BEAN

wooyeon06 2023. 3. 6. 15:38

 

1. BEAN

 : Spring에서 POJO(plain, old java object)를 ‘Beans’라고 부른다.
Beans는 애플리케이션의 핵심을 이루는 객체이며, Spring IoC(Inversion of Control) 컨테이너에 의해 인스턴스화, 관리, 생성된다.
Beans는 우리가 컨테이너에 공급하는 설정 메타 데이터(XML 파일)에 의해 생성된다.
컨테이너는 이 메타 데이터를 통해 Bean의 생성, Bean Life Cycle, Bean Dependency(종속성) 등을 알 수 있다.
애플리케이션의 객체가 지정되면, 해당 객체는 getBean() 메서드를 통해 가져올 수 있다.

 

2. Spring Bean 정의

 

주요 속성

  • class(필수): 정규화된 자바 클래스 이름
  • id: bean의 고유 식별자
  • scope: 객체의 범위 (sigleton, prototype)
  • constructor-arg: 생성 시 생성자에 전달할 인수
  • property: 생성 시 bean setter에 전달할 인수
  • init method와 destroy method

 

3. Spring Bean Scope

 

XML

<bean id="myBean" class="com.example.MyBean" scope="singleton"/>

<bean id="myBean" class="com.example.MyBean" scope="prototype"/>

<bean id="myBean" class="com.example.MyBean" scope="request"/>

<bean id="myBean" class="com.example.MyBean" scope="session"/>

<bean id="myBean" class="com.example.MyBean" scope="application"/>

 

 

SpringBoot JAVA

 

Scope Description
@Scope("singleton") 애플리케이션 컨텍스트에서 하나의 인스턴스만 생성됩니다. 이것이 기본값입니다.
@Scope("prototype") 빈이 요청될 때마다 새로운 인스턴스가 생성됩니다.
@Scope("request") HTTP 요청마다 인스턴스가 생성되고, 요청이 완료될 때까지 유지됩니다.
@Scope("session") HTTP 세션의 라이프사이클과 동일하게 유지됩니다.
@Scope("application") ServletContext와 동일한 라이프사이클을 가집니다.

 

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

@Configuration
public class AppConfig {
    
    @Bean
    @Scope("prototype")
    public MyPrototypeBean myPrototypeBean() {
        return new MyPrototypeBean();
    }
}

 

 

 

 

 

 

 


 

https://gmlwjd9405.github.io/2018/11/10/spring-beans.html

https://velog.io/@probsno/Bean-%EC%8A%A4%EC%BD%94%ED%94%84%EB%9E%80