Spring Ch 1. IoC 컨테이너(1) - 빈과 IoC


Dependency

  • 하나의 객체가 다른 객체를 변수로 가지고 있거나 파라미터로 전달, 혹은 메소드를 호출하는 것을 ‘의존한다’라고 표현한다.
  • 객체 A가 객체 B를 의존하고자 할 때 객체를 직접 선언하여 사용하나, 만약 객체 A가 객체 B 대신 객체 C를 사용하는 객체로 사용하기 위해서는 C에 의존하고 객체 A와 비슷한 객체 D를 선언해야 한다.

Dependency Inversion Principle

  • 의존하는 객체는 재사용할 수 없다. 객체를 재사용하기 위해서는 의존성을 제거하여야 한다.
  • 의존 대상이 되는 객체를 추상화하여 의존성을 제거할 수 있다. 이를 의존성 역전 원리(Dependency Inversion Principle)라고 한다.

IoC(Inversion of Control)

  • 의존성 역전 원리를 구현하는 기법중 하나.
  • 객체가 사용하는 의존 객체를 만들지 않고 주입 받아 사용하는 방식을 의미하며 이를 의존 관계 주입(Dependency Injection) 이라고도 한다.

IOC 컨테이너

  • IOC 기능을 제공하는 외부 객체를 IOC 컨테이너라고 한다.
  • IOC 컨테이너를 통해 객체의 생성, 설정, 제거 등의 작업을 수행하기 때문에 컨테이너가 객체의 제어권을 가지고 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//일반적인 제어
public class Service{
Repository repository = new Repository();
}
//IoC에서의 제어
@Repository
public class Repository{

}
@Service
public class Service{
Repository repository;

@autowired
public void setRepository(Repository repository){
this.repository = repository;
}
}

Bean

  • IOC 컨테이너가 관리하는 객체.
  • 컨테이너에서 객체를 주입받으므로 별도의 new 연산자를 필요로 하지 않는다.

XML을 이용한 빈 등록

  • Spring Framework에서 xml configuration file을 생성하여 빈을 등록할 수 있다.
  • Eclipse 환경에서는 New File -> Others -> Spring Bean Configuration File를 통해 생성.

eclipse 환경에서 configuration file 생성방법

  • 생성한 Configuration File을 다음과 같이 작성하여 bean을 설정할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
<!--  빈 설정  -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="service" class="com.example.demo.Service">
<property name="repository" ref="repository"/>
</bean>
<bean id="repository" class="com.example.demo.Repository"></bean>
<beans>
  • bean 태그로 빈을 설정할 수 있고 property태그로 내부의 객체를 주입할 수 있다.
  • bean 태그를 통해 선언하는 방법은 다수의 빈을 추가하고자 할 때마다 xml 파일을 수정해야하는 번거로움이 있다.

component scanner를 이용한 빈 설정

  • configuration 파일에 빈 스캐너를 선언하여 빈을 자동으로 등록할 수 있다.
  • conponent-scan 태그를 사용하기 위해 beans 태그에 다음의 내용을 추가해주어야 한다.
1
xmlns:context="http://www.springframework.org/schema/context"
  • context로 정의된 태그 component-scan을 beans태그 내부에 추가하여 빈 스캐너를 정의한다.
1
2
<!--빈 스캐너  -->
<context:component-scan base-package="com.example.demo"></context:component-scan>
  • 빈 스캐너는 @Service, @Repository와 같은 annotation이 설정된 객체를 찾아 컴포넌트로 등록한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Repository
public class Repository{

}
@Service
public class Service{
Repository repository;

@autowired
public void setRepository(Repository repository){
this.repository = repository;
}
}

댓글