1. Spring Tutorial

지니🧸·2023년 9월 12일
0

YC Tech Academy

목록 보기
2/5

연세대학교 미래교육원 x 코드프레소의 YC Tech Academy를 수강하기 위해 Spring Tutorial으로 예습한 개인 노트입니다.

Bean 주입

Bean이란?

Beans are the objects that:

  • form the backbone of your application
  • are managed by the Spring IoC container
  • instantiated, assembled, and otherwise managed by a Spring IoC container

IoC (Inversion of Control)

IoC: a process in which an object defines its dependencies without creating them

  • delegates the job of constructing such dependencies to an IoC container

Bean configuration

@Component
public class Company {
	...
}

Configuration class

@Configuration
@ComponentScan(basePackageClasses = Company.class)
public class Config {
	@Bean
    public Address getAddress() {
    	return new Address("High Street", 1000);
    }
}

위의 Configuration 클래스가 Address 타입의 bean을 만든다. @ComponentScan 어노테이션은 컨테이너가 Company 클래스를 담은 패키지 안에 bean을 보도록 지시한다.

IoC in Action

AnnotationConfigApplicationContext 클래스의 인스턴스를 만들어서 컨테이너를 빌드해야 한다

ApplicationContext conetxt = new AnnotationConfigApplicationContext(Config.class);

번외) Bean scopes

6 types of scopes: singleton, prototype, request, session, application, websocket

Singleton

Singleton scope에서 컨테이너는 빈의 단 하나의 인스턴스만 생성한다. 이 빈에 대한 모든 요청은 그 하나의 객체만 리턴할 것이고, 이 객체에 대한 변화는 빈의 모든 레퍼런스에 반영될 것이다.

scope을 명시하지 않으면 기본적으로 singleton으로 설정된다

@Bean
@Scope("singleton")
public Person personSingleton() {
	return new Person();
}

Prototype

Prototype scope: returns a different instance every time it's requested from the container

@Scope("prototype")

Web aware scopes

Request, Session, Application, Websocket scopes >> only available in a web-aware application context

사실 잘 사용되지는 않는다

  • Request scope: creates a bean instance for a single HTTP request
  • Session scope: creates a bean instance for an HTTP session
  • Application scope: creates bean instance for the lifecycle of a ServletContext
  • Websocket scope: creates bean instance for a particular WebSocket session

Bean과 Component 차이

@Bean

  • 메서드 레벨에서 사용된다
    • 일반적으로 @Configuration 어노테이션이 지정된 클래스 내에서 메서드로 정의된 메서드에 해당
  • 직접 빈 객체를 생성하고 구성하고자 할 때 사용한다

@Component

  • 클래스 레벨에서 사용된다
    • 해당 클래스는 스프링 컨테이너에 빈으로 등록된다
  • 주로 클래스를 빈으로 사용하고자 할 때 사용된다
  • @ComponentScan을 통해 클래스를 검색하고 자동으로 빈으로 등록하는 것이 일반적

Field Injection, Constructor Injection 차이

Field injection과 Constructor injection은 스프링 프레임워크에서 의존성 주입을 수행하는 두가지 방법이다.

Field injection

의존성을 클래스의 필드로 직접 주입하는 방식으로, 필드에 @Autowired, @Inject과 같은 주입 어노테이션을 사용하여 의존성을 주입한다.

  • 주로 간단한 경우에 사용한다
  • 필드 주입은 의존성이 변경되거나 테스트하기 어려울 수 있다
  • 순환 의존성 문제 발생 가능성 존재

@Resource를 사용한다

Constructor injection

클래스의 생성자를 통해 주입하는 방식이다. 클래스의 생성자에 필요한 의존성을 매개변수로 받고, 스프링이 이를 자동으로 주입한다

  • 의존성을 명시적으로 표현한다
    • 순환 의존성 문제 방지
  • 테스트하기 쉽다
  • 변경에 민감하지 않다
  • 코드가 복잡해질 수 있다
  • 여러개의 의존성이 필요할 때는 여러 개의 생성자 매개변수가 필요할 수 있다

@Primary, @Qualifier annotation

@Primary@Qualifier 어노테이션으로 같은 타입의 여러 빈을 구분할 수 있다

  • @Primary - designates a default bean that should be injected when no qualifier is specified
  • @Qualifier - specifies a specific bean that should be injected

@Qualifier takes precedence over @Primary.
= If both annotations are used, the bean annotated with @Qualifier will be injected

실습

@Configuration annotation 을 이용하여 H2 datasource를 설정해본 tutorial 수행 결과. dev spring profile 에서는 메모리에 저장하도록 설정, live spring profile 에서는 파일에 저장하도록 설정 하시면 됩니다.

https://github.com/becooq81/YC-TechAcademy/tree/step1

profile
우당탕탕

0개의 댓글