3. DI, IoC (2)
1. XML을 통한 빈 등록
- 토비의 스프링, 스프링3/4 시절까지 많이 사용
- 설정이 외부로 명확히 분리된 것을 알 수 있음
- 하지만 자동완성이나 컴파일 등으로 오타를 잡기 어렵고 타이핑 양이 많아짐
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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="cardAdapter" class="com.zerobase.convpay.service.CardAdapter"/>
<bean id="moneyAdapter" class="com.zerobase.convpay.service.MoneyAdapter"/>
<bean id="discountByConvenience" class="com.zerobase.convpay.service.DiscountByConvenience"/>
<bean id="conveniencePayService" class="com.zerobase.convpay.service.ConveniencePayService">
<constructor-arg name="paymentInterfaceSet">
<set>
<ref bean="cardAdapter"/>
<ref bean="moneyAdapter"/>
</set>
</constructor-arg>
<constructor-arg name="discountInterface" ref="discountByConvenience"/>
</beans>
2. XML ComponentScan을 통한 빈 등록
- 기본 빈 등록 방식은 클래스가 많을 경우 너무 번거로움
- 자동으로 등록해줄 수는 없을까?
- @Controller, @RestController, @Service, @Component, @Repository 등의 지정된 어노테이션이 붙은 클래스를 Bean으로 등록
1
2
3
4
5
6
7
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
<context:component-scan base-package="com.zerobase.convpay"/>
</beans>
3. JavaConfig를 통한 빈 등록
- 스프링4 때부터 XML이 아닌 JavaConfig가 많이 활용되기 시작함
- XML 설정파일이 자바 코드화 된 것
- 자동완성, 컴파일 시 정적 분석으로 오류를 잡아줌
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.zerobase.convpay.config;
import com.zerobase.convpay.service.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
import java.util.HashSet;
@Configuration
public class ApplicationConfig {
@Bean
public ConveniencePayService conveniencePayService(){
return new ConveniencePayService(
new HashSet<>(Arrays.asList(moneyAdapter(), cardAdapter())),
discountByConvenience()
);
}
@Bean
public CardAdapter cardAdapter() {
return new CardAdapter();
}
@Bean
public MoneyAdapter moneyAdapter() {
return new MoneyAdapter();
}
@Bean
public DiscountByConvenience discountByConvenience() {
return new DiscountByConvenience();
}
}
4. JavaConfig ComponeneScan을 통한 빈 등록
- XML의 설정 방법
- JavaConfig에서의 설정 방법
- 스프링 부트에서는 이 방식이 기본적으로 적용되어 있으며, 그래서 편리하게 빈 등록 가능
1
2
3
@Configuration
@ComponentScan(basePackageClasses = ConvpayApplication.class)
public class ApplicationConfig {}
This post is licensed under CC BY 4.0 by the author.