[Spring 이해하기 5] Spring Bean (스프링 객체)
[1] Spring Bean이란?
: Spring Framework가 관리하는 클래스의 인스턴스(Instance)를 Spring Bean이라 함
: Spring Bean 인터페이스와 클래스 POJO(Plain Old Java Object)로 정의됨
1. Spring Bean 생성
- XML 설정 파일
<bean id=”serviceImpl” class=”com.dongjoo.ex.service.impl.ServiceImpl”>
- id - Atrribute: Bean 식별자
- class - Atrribute: Bean 객체의 구현 클래스 타입의 전체 경로
- @Configuragtion 설정 클래스
@Configuration public void AppConfiguration(){}
- 빈 설정 - @Bean 어노테이션이 붙여진 메소드로 정의
//ServiceImpl(클래스)의 객체를 반환 @Bean ServiceImpl serviceImpl(){ return new ServiceImpl(); } //Service(인터페이스)를 구현한 ServiceImpl 객체를 반환 @Bean Service serviceImpl(){ return new ServiceImpl(); }
- 메소드 이름: 빈 객체 명
- 메소드 리턴 타입: 빈 객체의 타입
- 빈 메소드: 빈 객체 구현 클래스의 인스턴스를 반환
2. IoC Container
: 빈 생성관리, 인스턴스 의존성 관리를 담당한다
: Spring Bean의 인스턴스를 생성하기 위해서는 먼저 생성된 Bean 인스턴스를 관리하는 IoC Container가 필요하다
- ApplicationContext 인터페이스
: IoC Container를 표현함 - Application Context
: IoC container를 자체를 의미함
3. Application context 생성 방법
- ClassPathXmlApplicationContext 클래스
ApplicationContext ctx = new ClassPathXmlApplicationContext(“servlet-context.xml”);
- servlet-context.xml
: Java CLASSPATH에서 지정된 설정 파일
- servlet-context.xml
- FileSystemXmlApplicationContext 클래스
ApplicationContext ctx = new FileSystemXmlApplicationContext(“src/servlet-context.xml”);
- servlet-context.xml
: 파일 시스템의 절대 경로 및 상대 경로로 지정된 설정 파일
- servlet-context.xml
- AnnotatonConfigApplicationContext 클래스
ApplicationContext ctx= new AnnotationConfigApplicationContext(AppConfiguration.class);
- AppConfiguration.class
: Spring Bean 설정 클래스
- AppConfiguration.class
- Bean 호출(Call)
Service service = (Service)ctx.getBean(“service”);
- Service(인스턴스)의 빈을 가져온다.
- Spring Bean 클래스는 항상 매개변수가 없는 디폴트 생성자를 요구한다. "구현 해야 된다"
4. Bean Scope (영향 범위)
: Spring Bean 인스턴스가 생성될 때 생성되는 Scope를 설정 가능
- singleton
: ApplicationContext 컨테이너당 하나의 인스턴스 생성 - "default" - prototype
: getBean()메소드가 호출될 때마다 하나의 인스턴스 생성 - request
: HTTP request 범위 안에서 인스턴스 생성 - session
: HTTP Session 범위 안에서 인스턴스 생성 - global-session
: 전역 HTTP session 범위 안에서 인스턴스 생성
//xml <bean id=”service” class=”com.dongjoo.ex.service.Service” scope=”prototype”> //java @Bean @Scope(“prototype”) //parameter(범위) 변경하여 사용가능 Service service(){ return new Service(); }
5. Bean의 Life Cycle(생명주기)
: 일반 Java 클래스의 인스턴스를 생성할때 생성자(Constructor)가 호출되고 소멸될때 소멸자 (Finalize)가 호출된다
: Spring Bean도 생성과 소멸의 메소드를 지정할 수있다.
- init-method
: 인스턴스 초기화시 호출되는 메소드 - destroy-method
: 인스턴스 소멸시 호출되는 메소드
<bean id=”service” class=”com.dongjoo.ex.service.Service” scope=”prototype” init-method=”init” destroy-method=”destroy”/>
- Factory Method Pattern(팩토리 메소드 패턴): Bean을 생성해주는 Factory를 활용 "주로 Singleton 인스턴스 생성시 사용"
//xml - Bean 인스턴스 생성 <bean id=”service” class=”com.dongjoo.ex.service.impl.ServiceImpl” factory-method=”getInstance”/> //클래스 public class ServiceImpl implements Service{ private ServiceImpl(){} private Static class FactoryHolder{ static Service instance = new ServiceImpl(); } private static Service getInstance(){ return FactoryHolder.instance; } }
- Spring Bean은 default가 Singleton 객체로 생성되기 때문에 사실상 선언이 그닥 별로 필요없다.
6. Spring Bean vs Java Bean
- Spring Bean
: IoC Container, application context 안에서 생성 및 관리되는 Java 클래스의 인스턴스 - "IoC Container 내부에 존재" - Java Bean
: IoC Container, application context에서 관리되지 않고 외부에서 new 연산자를 사용하여 인스턴스를 생성하는 빈 - "IoC Container 외부에 존재"
: java 클래스의 인스턴스(instance)를 모두 Spring Bean으로 만들수 있지만 Service Layer, Repository Layer에 포함되는 클래스만하는 것을 권장한다
"Spring Bean 클래스로 사용하면 IoC Container에 과 부하(Over Load) 방지"
"Domain 클래스(DTO), Mode클래스, Entity클래스 는 Spring Bean으로 만들자"
'WEB > Spring MVC' 카테고리의 다른 글
[Spring 이해하기 4] Dependency Injection 개념 (Spring 삼각형 1 - 의존 주입) (0) | 2021.10.05 |
---|---|
[Spring 이해하기 3] Framework란? (0) | 2021.10.04 |
[Spring 이해하기 2] Spring Framework & 기본 도구 개요 (0) | 2021.10.04 |
[Spring 이해하기 1] Java Web Application (0) | 2021.10.04 |