[자바 스프링] 스프링 빈(Spring bean) IoC컨테이너란?
[자바 스프링] 스프링 빈(Spring bean) IoC컨테이너란? — #자바스프링 #스프링빈 #SpringBean #IOC컨테이너 #ioc컨테이너란 #SpringBean이란? #개발자의도구...
#자바스프링 #스프링빈 #SpringBean #IOC컨테이너 #ioc컨테이너란 #SpringBean이란? #개발자의도구들
AI스쿨 msa기반 java 백엔드 코스 중에 공부한 내용을 작성하였습니다
\* 현재 웹 서버 프로젝트를 진행중입니다. 전체적인 목차를 보시려면 여기에서 참고하세요
\* 전체코드: https://github.com/keyveloper/HTTP\_server.git
Spring Bean이란?
이전글에서 Bean에 대해 다뤄 보며 Java Bean에 대해 공부하였습니다. 이번에는 Spring에서 사용하는 Spring Bean에 대해 알아보고, Java Bean과 어떤 차이가 있는지에 대해 공부해보겠습니다.
Spring framework 공식문서에 따르면 Spring내에서 Bean이라 불리우는 것들에 대한 정의는 이렇습니다.
| 어플리케이션의 주축이 되며, Spring IoC Container에 의해 관리되는 객체들을 Bean(Spring bean)이라고 부른다. |
|---|
여기서 IoC에 대한 개념이 아마도 Spring Bean의 핵심적인 개념이 되겠습니다.
Inversion of Control Container
IoC와 DI
Spring을 좀 더 잘 이해하기 위해서는 IoC에 대한 개념이 필요합니다. 또한 Dependecy Injection이라는 개념도 공부해야합니다.
이는 제가 따로 글을 정리해두었으니 여기를 참고해주세요.
Ioc container
Spring은 다른 프레임워크와 달리 독특한 특징을 가지는 프레임워크입니다. 가장 독특하다고 말 할 수 있는 부분은 바로 IoC 컨테이너의 존재인데요. 이는 개발자가 직접 관리하는 Bean을 프레임워크가 알아서 관리해주는 기능을 가지고 있습니다.
IoC덕분에 Spring 프레임워크를 사용하는 개발자들은 Bean의 scope나 lifeCycle 등을 신경쓰지 않고 오로지 기능적인 측면에서만 코드를 작성하도록 돕습니다.
아래 IoC를 통한 Speing Bean 사용예시를 통해 더 알아보겠습니다.
Using of IoC container
| public class Address { private String street; private int number; public Address(String street, int number) { this.street = street; this.number = number; }} |
|---|
| import lombok.Data;@Datapublic class Company { private Address address; public Comapny(Address address) { this.address - address; }} |
|---|
| Address address = new Address("High Street", 1000);Company company = new Company(address); |
|---|
기존에는 Company와 Address가 존재하는 경우, 해당 객체를 새로 생성해야 사용할 수 있었습니다. 하지만 Spring Bean을 사용하게 되면, Bean으로 등록된 객체는 Spring이 알아서 생성하고, 제거까지 관리합니다.
Spring Bean 등록 방법
그럼 사용하고자하는 객체를 Bean으로 만들어 관리하면 매우 편리하겠죠? 이번에는 Spring에서 어떻게 객체를 Bean으로 등록하는지에 대해 알아보도록 하겠습니다.
Simple Register
가장 간단한 방법으로는 @(annotation)을 사용하는 것입니다. 원하는 객체에 @을 붙이면 되는데요. 어떤 anotation을 사용하면 되는지 알아봅시다.
@Component
| @Componentpublic class MyComponent {} |
|---|
SpringBean으로 만들기 위한 가장 일반적인 Annotation으로 다른 annotation의 뿌리가 되는 annotation으로 보시면 됩니다. 이제 @Component가 붙은 객체는 Bean이 됩니다.
@Service
| @Servicepublic class MyService {} |
|---|
@Service는 비지니스 로직을 처리하는 서비스 계층 클래스에 사용됩니다. 여기서 서비스 계층은 MVC pattern에서 다시 설명할 것인데, 여기서 간략하게 설명하자면 Model과 Controller사이에 있는 계층으로 생각하시면 됩니다.
@Repository
| @Repositorypublic class MyDataBase {} |
|---|
@Repository는 데이터 저장소 역할을 하는 객체를 표기할 때 사용합니다.
@Controller
| @Controllerpublic class MyController {} |
|---|
MVC에서의 Contoller역할을 하는 객체를 표현할 때 사용하는 annotation입니다. 주로 웹서버에서 웹 요청을 처리하는 클래스에 사용되는데, 웹 요청 처리 기능을 제공합니다.
이와 같이 Bean으로 등록하는 방법은 간단하게 @을 붙이는 것만으로도 가능합니다. 뿐만아니라, 그 역할에 따라 Spring에서 자동으로 여러 기능들을 부여하는 역할도 수행합니다. 예를 들어 Contoller를 객체에 부여하면, 해당 객체는 웹 Request를 처리하는 methode를 지원받습니다.
Configuration
@Configuration으로도 원하는 객체를 Bean으로 등록할 수 있게 해줍니다. @Configuration은 특수한 상황에서 사용되는데, 가령 Spring으로 만들어지지 않는 객체를 외부에서 받아와 IoC에 등록하고자 할 때 사용할 수 있습니다. (생성자가 반드시 필요한 객체, 다른 라이브러리로 제공되어서 @어노테이션 받을 수 없다)
@Configuration이 붙은 객체의 @Bean method가 반환하는 객체는 Spring Bean이 됩니다.
| @Configuration public class AppConfig { @Bean public MyBean myBean() { return new MyBean(); } } |
|---|
이제 AppCongif의 myBean() 메서드가 반환하는 객체 MyBean은 IoC에 의해 관리됩니다.
\* 쓸일이 많이 없다고 한다.
Spring Bean Management
앞서서 Spring Bean은 Spring이 자동으로 관리를 해준다고 말하였습니다. 하지만, 원하는 경우 개발자가 직접 Bean 범위 및 생명주기를 관리할 수 있습니다.
여기서는 일반적인(defalt로 사용되는) Spring Bean의 Scope에 대해서만 알아보겠습니다.
Spring Bean Scope
Spring Bean은 기본적으로 Singleton 패턴으로 생성됩니다. 디자인 패턴을 공부해보신 분들이라면 아시겠지만, Single ton pattern은 어플리케이션 내에 단 하나의 인터페이스로 생성되어 모든 객체에서 공유됩니다.
이 외에도 prototye, session, request 등 다양한 패턴으로 생성이 가능하지만, 현실적인 이유로 사용하지 않는다고 합니다.
그 이유는 singleton이외의 패턴으로 생성시, IoC가 객체를 생성할 때마다, 계속해서 @에 해당하는 기능들을 붙여줘야 합니다. (초기 POJO는 아무런 기능이 없는 객체입니다) 한 두번만 사용되는 객체라면 크게 문제될게 없겠지만, 자주 사용하는 객체라면 객체 생성마다 기능을 부여하여 overhead가 발생할 수 잇습니다. 고로, 최초 한번만 기능을 부여하도록 하는 Singleton 패턴이 가장 현실적인 Scope가 되겟습니다.
(\* 자바의 weaving 개념에 대해 공부)
Java Bean vs Spring Bean
이전글을 통해 JavaBean에 대해 정리를 했었는데요. Spring Bean과의 차이를 보며, 개념정리를 다시 한번 해볼 수 있겠습니다.
| Criteria | Java Bean | Spring Bean |
|---|---|---|
| Definition | A standard Java class that follows specific conventions. | An object managed by the Spring IoC (Inversion of Control) container. |
| Constructor | Must have a public default (no-argument) constructor. | Doesn't strictly require a public no-arg constructor unless a bean is being created using the constructor approach in XML configuration. |
| Accessibility | Properties are accessed via getter and setter methods. | Same as Java Bean, but it's managed by the Spring container. |
| Life Cycle | Managed by the developer or Java environment. | Managed by the Spring container. Can be a singleton, prototype, etc. |
| Configuration | No special configuration is required. | Configured using XML, annotations, or Java configurations in the Spring context. |
| Serializable | Typically should implement the Serializable interface.-> for enperprise java Bean | Serialization isn't a strict requirement unless needed for a specific use case. |
| Framework Dependency | Not tied to any framework. | Specific to the Spring framework. |
| Use Case | Used for encapsulating many objects into a single object (bean) to simplify data representation. | Used for managing dependencies, life cycles, and configurations in Spring applications. |
| Scope | No inherent scope management. | Can be managed by Spring to be a singleton, prototype, request, session, etc. |
| Annotation | No standard annotations; purely convention-based. | Can utilize a variety of Spring-specific annotations like @Component, @Service, @Repository, etc. |
출처 : https://www.javaguides.net/2023/08/java-bean-vs-spring-bean.html
[Java Bean vs Spring Bean
A Java Bean is a standard Java class that follows specific conventions.A Spring Bean is an object managed by the Spring IoC
www.javaguides.net](https://www.javaguides.net/2023/08/java-bean-vs-spring-bean.html)