삶 가운데 남긴 기록 AACII.TISTORY.COM
Spring bean 본문
Spring bean
스프링 프레임워크가 관리하는 클래스들의 모든 인스턴스 객체들을 Spring bean 이라고 합니다.
Spring Framework에서 "Bean"은 Spring IoC(Inversion of Control) 컨테이너에 의해 인스턴스화, 구성 및 관리되는 객체(Object)를 의미합니다.
Spring Bean의 특징:
- 관리 주체: 객체의 생성(인스턴스화), 설정(의존성 주입), 생명주기(초기화, 소멸)를 Spring IoC 컨테이너가 전적으로 관리합니다.
- 설정: 클래스에 @Component, @Service, @Repository, @Controller와 같은 Stereotype 애노테이션을 붙이거나, @Configuration 클래스 내부의 @Bean 메서드를 통해 등록합니다.
- 규약: Spring Bean은 필수적으로 JavaBeans 규약을 따를 필요는 없습니다. 일반적인 자바 클래스일 수도 있고, 인터페이스를 구현한 클래스일 수도 있습니다. 물론, 데이터 객체의 경우 JavaBeans 규약을 따를 수도 있지만, 이는 필수가 아닙니다.
Spring bean 설정 방법
XML로 설정 할 때에는 아래 처럼 설정합니다.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bean객체를식별하는id값" class="bean객체가정의된클래스의패키지경로" />
</beans>
어노테이션을 이용해서 설정할 때에는 아래처럼 클래스 위에 @Configuration 어노테이션을 설정하고, 메서드 위에는 @Bean 어노테이션을 설정해 줍니다.
패키지 경로는 net.aacii.app 으로 가정합니다.
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import net.aacii.app.service.SampleService;
import net.aacii.app.service.SampleServiceImpl;
@Configuration
public class AppConfig {
@Bean
SampleService sampleService() {
return new SampleServiceImpl();
}
}
IoC 컨테이너
Spring bean 인스턴스를 생성하기 위해 IoC 컨테이너를 먼저 생성해야 합니다.
IoC컨테이너는 bean 인스턴스들간의 의존성을 관리합니다.
ApplicationContext 인터페이스는 이러한 IoC 컨테이너의 인터페이스 입니다.
ApplicationContext는 일반적으로 아래처럼 생성 할 수 있습니다. (beans.xml은 bean이 정의된 xml파일입니다.)
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
만약 파일 시스템의 절대 경로를 지정한다면 아래 처럼 생성 할 수 있습니다.
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/main/java/beans.xml");
만약 위의 예제 처럼 AppConfig class 파일로 IoC 컨테이너를 생성할 때는 아래처럼 할 수 있습니다.
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
ApplicationContext에 bean 인스턴스가 생성될 때, 생성되는 Scope를 정할 수 있습니다.
singleton은 ApplicationContext 하나 당 하나의 인스턴스를 생성합니다.(기본값)
prototype은 getBean()메서드가 호출될 때마다 하나의 인스턴스를 생성합니다.
request는 HTTP request 영역 안에 인스턴스가 생성됩니다.
session은 HTTP session 영역 안에 인스턴스가 생성됩니다.
global-session은 전역 HTTP session 안에서 인스턴스가 생성됩니다.
예를 들어 xml의 경우
<bean id="bean객체를식별하는id값" class="bean객체가정의된클래스의패키지경로" scope="prototype" />
처럼 scope를 지정해 줄 수 있습니다.
클래스 파일을 사용하는 경우에는 @Scope 어노테이션으로 지정합니다.
@Bean
@Scope("prototype")
SampleService sampleService(){
return new SampleServiceImple();
}
Bean 인스턴스(객체) 의 생성 소멸
java에서 인스턴스가 생성 될 때 생성자가 호출되고 소멸할 때 소멸자가 호출됩니다.
bean 인스턴스도 마찬가지 인데, 생성될 때 호출 되는 메서드와 소멸될 때 호출되는 메서드를 지정할 수 있습니다.
xml 의 예)
<bean id="bean객체를식별하는id값" class="bean객체가정의된클래스의패키지경로" init-method="init" destroy-method="cleanUp" />
class 의 예)
public class SampleServiceImpl implements SampleService{
public void init(){
}
public void cleanUp(){
}
}
팩토리 패턴의 예)
<bean id="bean객체를식별하는id값" class="bean객체가정의된클래스의패키지경로" factory-mehtod="getInstance" />
public class SampleServiceImpl implements SampleService{
private SampleServiceImpl(){
}
private static class FactoryHolder{
static SampleService instance = new SampleServiceImpl();
}
public static SampleService getInstance(){
return FactoryHolder.instance;
}
}
'DEV&OPS > Java' 카테고리의 다른 글
| Spring AOP (0) | 2025.11.05 |
|---|---|
| Spring 주요 어노테이션 (0) | 2025.11.05 |
| Spring MVC 프로젝트 구조 (1) | 2025.11.05 |
| Spring 의존성 주입과 제어의 역전 (0) | 2025.11.04 |
| 리스너(Listener) : 옵저버(observer) 패턴 (0) | 2025.11.03 |
