Spring/스프링 기본

Bean이란?

공대키메라 2022. 1. 28. 18:16

Bean이란 무엇인가? 콩인가? (노잼...)

ㄴㅈ...

 

 

Spring으로 개발을 하다보면 Bean이라는 말을 굉장히 많이 사용할 것이다. (그렇다고 해줘!)

 

필자는 어떤 것을 이해했다는 기준을 한줄로 정리할 수 있느냐로 보고있다.

 

Bean은 Spring Framework의 핵심 개념이라고 하는데 과연 정확히 한줄로 어떻게 설명할 수 있을까?

 

그럴 수 있었으면 내가 이것을 작성하지 않았을 것이다. (머쓱...)

 

그래서 이번 블로그 정리를 통해 Bean이란 무엇이고 이를 어떻게 관리하고 등록해서 사용할 수 있는지 정리하려고 한다. (빵긋 ^^)

 

1. The Definition of Spring Bean

이에 대한 정보를 baeldung 사이트에서 확인할 수 있었다. 

 

참고 : https://www.baeldung.com/spring-bean

 

In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans.
A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.

 

스프링에서, 스프링 제어 역전 컨테이너에 의해 관리되고, 당신의 애플리케이션의 핵심을 형성하는 객체들을 bean이라고 부른다!
빈은 인스턴스화되고, 조립되고, IoC Container에의해 관리된다. 

 

의미의 정의와 함께 baeldung에서는 과거의 코드와 현재 bean 을 적용한 코드의 차이점을 들며 설명하고 있다. 

 

Traditional Approach

Normally, we create objects with their classes' constructors:

----------------------
Address address = new Address("High Street", 1000);
Company company = new Company(address);
----------------------

There's nothing wrong with this approach, but wouldn't it be nice to manage the dependencies in a better way?
Imagine an application with dozens or even hundreds of classes. Sometimes we want to share a single instance of a class across the whole application, other times we need a separate object for each use case, and so on.

Managing such a number of objects is nothing short of a nightmare. This is where inversion of control comes to the rescue.

Instead of constructing dependencies by itself, an object can retrieve its dependencies from an IoC container. All we need to do is to provide the container with appropriate configuration metadata.

 

전통적인 접근

일반적으로, 우리는 그들의 클래스의 생성자를 통해 객체를 생성한다. 
----------------------
Address address = new Address("High Street", 1000);
Company company = new Company(address);
----------------------

이 접근에 잘못된 건 없지만 더 나은 방법으로 의존성을 관리하면 좋지 않을까? 

수십 혹은 수백개의 클래스가 있다고 떠올려봐라. 때때로 우리는 전체 애플리케이션 사이중 하나의 인스턴스를 공유하길 원하고 다른 때에는 각각 사용 경우를 위해 분리된 객체를 필요로 하거나 할 수 있다.
(여러개의 클래스를 다양한 방식으로 사용하고 싶다는 말이군...)

많은 객체를 관리하는 것은 진짜 미치는짓이다! 이것이 IoC가 필요한 이유다.

그것 자체로(생성자를 직접 만들어서 말이다!) 의존성을 생성하는것 대신에 객체는 IoC 컨테이너로부터 의존성을 되찾아 올 수 있다. 우리가 해야할 것은 컨테이너에 적절한 구성 metadata를 제공하는 것이다!

 

그러니까 정리를 하자면 객체를 java class파일 안에서 선언해서 사용하게 되면 의존성을 우리가 직접 주입(Dependendy Injection!)하는 것이다. 

 

하지만 이것을 일일이 선언하지 않고 IoC Container에 적절한 metadata를 제공하면 이것을 직접 만들지 않고 원하는 곳에 인스턴스를 공유할 수 있다는 것이다.

 

IoC container는 우리가 직접 의존성을 주입하고 하던 작업을 자동으로 해주는 역할을 한다. 결국  IoC Container에 의해 관리되는 오브젝트들을 Bean이라고 하며 외부로부터 주입하는 방식으로 도와준다는 거네! 그게 굉장히 편하고!

 

 

 

2. Bean 등록하기

Bean을 등록하는 방식은 하나만 있는 것이 아니다. 물론 나같으면 편리한 한 방식만 주로 사용하겠지만 상황에 따라서 적절히 해야 할 것이다. 

 

이에 대한 방식을 찾아보려니 잘 정리된 블로그가 있어서 참고 주소를 첨부한다. 

 

  1. xml 태그로 등록하기
  2. xml-component scan 사용하기 
  3. Config파일을 통한 Bean 등록
  4. Config의 ComponentScan을 활용한 Bean 등록

 

참고 : https://seongmun-hong.github.io/spring/Spring-Bean-Create

 

3. @Component vs @ComponentScan

 

@ComponentScan 어노테이션은 @Component 어노테이션 @Service, @Repository, @Controller 등의 어노테이션에 부여된 Class들을 자동으로 Scan하여 Bean으로 등록해주는 역할을 하는 어노테이션이다. 

 

우리가 Layer 를 나누기 위해 사용했던 @Service, @Repository, @Controller도 결국 Bean을 등록하는 행위였던 것이다!

 

https://www.baeldung.com/spring-component-repository-service

 

이 내용을 또 알아가다보니 Component 와 Service Repository 어노테이션의 차이점을 설명하고 있다. 

 

Spring Annotations

In most typical applications, we have distinct layers like data access, presentation, service, business, etc.
Additionally, in each layer we have various beans. To detect these beans automatically, Spring uses classpath scanning annotations.

Then it registers each bean in the ApplicationContext.
Here's a quick overview of a few of these annotations:

@Component is a generic stereotype for any Spring-managed component.@Service annotates classes at the service layer.@Repository annotates classes at the persistence layer, which will act as a database repository.
We already have an extended article about these annotations, so we'll keep the focus here to the differences between them.

 

스프링 어노테이션

대부분의 전형적인 어플리케이션에서, 우리는 데이터 접근, 프레젠테이션, 서비스, 비즈비스 기타 등등의 분명한 계층을 가집니다. 추가적으로, 각각의 계층에서 우리는 다양한 빈을 가집니다. 자동적으로 이러한 빈들을 감지하기 위해, 스프링을 classpath scanning 어노테이션을 사용합니다. 

그리고 나서 ApplicationContext에 각각의 빈을 등록합니다. 
여기 이러한 어노테이션 몇개의 간략한 설명이 있습니다. 

@Component 는 어떤 스프링에 의해 관리되는 컴포넌트를 위한 일반적인 Stereotype입니다.
@Service는 서비스 레이어에서 클래스들을 어노테이트한다. 
@Repository는 영속 레이어에서 클래스들을 어노테이트한다.(데이터베이터 저장소처럼 행동한다!)
우리는 이미 이러한 어노테이션들에 대해 확장된 글을 가지고있다. 그래서, 여기서는 그들 사이에 차이점에 대해 집중할것이다. 

 

호오... 결국 layer를 구분해서도 등록할 수 있게 Spring에서 기능을 적절히 분리한 어노테이션을 제공하던 거였구나...

 

 

 

그러면 결국 Bean이란..

 

스프링에서, 스프링 제어 역전 컨테이너에 의해 관리되고, 당신의 애플리케이션의 핵심을 형성하는 객체들을 bean이라고 부른다!

 

 

 

 

 

'Spring > 스프링 기본' 카테고리의 다른 글

Glory of Rest 란 뭘까? + HATEOS 적용기  (0) 2022.02.16
Spring Web Socket 적용하기  (2) 2022.02.04
Spring VS Spring boot  (3) 2022.02.03
@Json~~~ 관련 annotation 정리  (0) 2022.02.03
MVC 어노테이션 정리  (0) 2022.01.19