연세대학교 미래교육원 x 코드프레소의 YC Tech Academy를 수강하기 위해 Spring Tutorial으로 예습한 개인 노트입니다.
Beans are the objects that:
IoC: a process in which an object defines its dependencies without creating them
@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을 보도록 지시한다.
AnnotationConfigApplicationContext
클래스의 인스턴스를 만들어서 컨테이너를 빌드해야 한다
ApplicationContext conetxt = new AnnotationConfigApplicationContext(Config.class);
6 types of scopes: singleton, prototype, request, session, application, websocket
Singleton scope에서 컨테이너는 빈의 단 하나의 인스턴스만 생성한다. 이 빈에 대한 모든 요청은 그 하나의 객체만 리턴할 것이고, 이 객체에 대한 변화는 빈의 모든 레퍼런스에 반영될 것이다.
scope을 명시하지 않으면 기본적으로 singleton으로 설정된다
@Bean
@Scope("singleton")
public Person personSingleton() {
return new Person();
}
Prototype scope: returns a different instance every time it's requested from the container
@Scope("prototype")
Request, Session, Application, Websocket scopes >> only available in a web-aware application context
사실 잘 사용되지는 않는다
ServletContext
WebSocket
session@Configuration
어노테이션이 지정된 클래스 내에서 메서드로 정의된 메서드에 해당@ComponentScan
을 통해 클래스를 검색하고 자동으로 빈으로 등록하는 것이 일반적Field injection과 Constructor injection은 스프링 프레임워크에서 의존성 주입을 수행하는 두가지 방법이다.
의존성을 클래스의 필드로 직접 주입하는 방식으로, 필드에 @Autowired
, @Inject
과 같은 주입 어노테이션을 사용하여 의존성을 주입한다.
@Resource
를 사용한다
클래스의 생성자를 통해 주입하는 방식이다. 클래스의 생성자에 필요한 의존성을 매개변수로 받고, 스프링이 이를 자동으로 주입한다
@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 에서는 파일에 저장하도록 설정 하시면 됩니다.