Bean Setup (cont`d)

Download Report

Transcript Bean Setup (cont`d)

Spring 2.5 programming

- Spring DI(Dependency Injection)

2009.07.21

Naver

지식iN서비스개발팀 임수민

목차 1. Spring container 2. Bean setup 1. Constructor method 2. Property method 3. Auto-wire 3. Life cycle 4. External setup property 5. Message globalization 6. Event 7. Annotation-based setup 8. Component Scan

1

Spring Container

 

빈 객체 저장 각 객체 간의 의존관계를 관리 3 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

1

Spring Container DI 제거

4 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

1

Spring Container (cont’d) Bean Factory Interface

Org.springframework.beans.factory.BeanFactory 인터페이스

   빈 객체를 관리하고 의존관계 설정해주는 기능을 제공하는 가장 단순한 컨테이 너 XmlBeansFactory가 구현클래스로 쓰임 Ex) 특정파일로부터 설정파일을 읽어오는 XmlBeanFactory 객체 생성, 빈 사용 Resource resource = new FileSystemResource(“beans.xml”); XmlBeanFactory factory = new XmlBeanFactory(resource); ParserFactory factory = (ParserFactory)factory.getBean(“parserFactory”);

5 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

1

Spring Container (cont’d) ApplicationContext & WebApplicationContext interface

org.springframework.context.

ApplicationContext

  

Interface

BeanFactory 인터페이스 상속받은 인터페이스 다양한 추가기능을 가지고 있어 가장 많이 쓰임 웹 어플리케이션 당 한 개의 Web ApplicationContext 존재 

org.springframework.context.support.

ClassPathXmlApplicationContext

 클래스 패스에 위치한 XML 파일로부터 설정 정보 로딩 String configLocation = “config/applicationContext.xml” ApplicationContext context = new ClassPathXmlApplicationContext(configLocation); 

org.springframework.context..

support.

FileSystemXmlApplicationContext

org.springframework.context.support.

XmlWebApplicationContext 6 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

1

Spring Container (cont’d) ApplicationContext & WebApplicationContext interface (cont’d)

web.xml 파일에서 다음과 같이 리스터 등록

contextConfigLocation WEB-INF/applicationContext.xml org.springframework.web.context.ContextLoaderListener

7 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

1

Spring Container (cont’d) XML스키마를 이용한 스프링 설정

”>

.jar 파일에 포함된 파일을 내부적으로 처리하기 때문에 XML이나 DTD 스키마 파 일에 URL을 올바르게 입력하면 인터넷 연결 상관없이 설정 파일 로딩 가능 8 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup 빈(bean)생성과 의존 관계 설정

빈 생성 및 사용 생성할 빈 객체의 클래스 이름

Resource resource = new ClassPathResource(“applicationContext.xml”); BeanFactory beanFactory = new XmlBeanFactory(resource); MysqlArticleDao articleDao = (MysqlArticleDao)beanFactory.getBean(“articleDao”);

9 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup 빈(bean)생성과 의존 관계 설정 (cont’d)

MysqlArticleDao 클래스

public class MysqlArticleDao implements ArticleDao{ //파라미터를 갖는 생성자가 정의되어있는 경우, 기본 생성자 추가 public MysqlArticleDao(){ } public MysqlArticleDao (DataSource dataSource){ ….

} } 

빈 팩토리 매서드

public class ParserFactory{ private static ParserFactory instance = new ParserFactory(); public static ParserFactory getInstance() { return instance; } } private ParserFactory() { }

10 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup 빈(bean)생성과 의존 관계 설정 (cont’d)

 직접 설정하여 스프링 컨테이너는 생성자를 사용하지 않고 ParserFactory 클래스 객 체를 구함

11 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup 의존 관계 설정 방식 4가지

생성자 방식

프로퍼티 설정 방식

XML 네임스페이스를 이용한 프로퍼티 설정

임의 빈 객체 전달 12 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup 생성자 방식

태그를 이용하여 의존하는 객체를 전달  - xml 설정 & -java 설정

or

//JAVA 에서 public class TestServiceSpring { private TestDao testDao; public TestServiceSpring(TestDao testDao) { } this.testDao = testDao; ...

13 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup (cont’d) 프로퍼티 설정 방식

 setXXX() 형태의 설정 메소드를 통해서 필요한 객체와 값을 전달받음  XML 설정

자바 소스

public class TestServiceSpring implements TestService {

private TestDao testDao; public void setTestDao(TestDao testDao) { this.testDao = testDao; }

} ...

14 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup (cont’d) XML 네임스페이스를 이용한 프로퍼티 설정

태그가 아닌 XML 네임스페이스를 이용하여 설정   네임스페이스가 http://www.springframework.org/schema/p 인 접두어를 사용 기본 데이터 타입 ("p:프로퍼티이름" 속성) 으로 프로퍼티 값 설정  빈 객체를 프로퍼티에 전달 ("p:프로퍼티이름-ref" 속성)  - xml 설정

15 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup (cont’d) 임의 빈 객체 전달

 식별 값을 갖지 않는 빈 객체를 생성하여 전달   식별 값을 갖지 않기 때문에, 임의 빈 객체는 재사용 불가 태그에 id나 name 속성을 사용하여 식별 값을 주어도 해당 식별 값은 사용 불가

16 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

2

Bean Setup (cont’d) Auto-wire

 스프링은 의존하는 빈 객체의 타입이나 이름을 이용하여 의존 객체를 자동으로 설 정 가능     byName : 프로퍼티의 이름과 같은 이름을 갖는 빈 객체를 설정 byType : 프로퍼티의 타입과 같은 타입을 갖는 빈 객체를 설정 constructor : 생성자 파리미터 타입과 같은 타입을 갖는 빈 객체를 생성자에 전 달 autodetect : constructor 방식을 먼저 적용하고, byType 방식을 적용하여 의존 객체를 설정  디버깅이 어려운 단점

17 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

3

Life Cycle (cont’d)

 스프링 컨테이너에 저장되는 빈 객체는 최소한 생성, 초기화, 소멸의 라이프 사이클 을 갖게 됨  생성, 초기화, 소멸뿐만 아니라 추가적인 단계를 통해 라이프 사이클에 따른 빈 객 체의 상태를 정교하게 제어 가능

18 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

3

Life Cycle (cont’d)

 [인터페이스.메서드이름]으로 표시된 단계는 빈 클래스가 지정한 인터페이스를 구 현했을 경우 스프링 컨테이너가 지정한 메서드를 호출  ex) BeanNameAware.setBeanName() 는 빈 클래스가 BeanNameAware 인터페 이스를 구현했을 경우 setBeanName() 메서드가 호출된다는 것을 의미  커스텀 init-method 는 태그의 init-method 속성에서 지정한 메서드가 호출  커스텀 destroy-method는 태그의 destroy-method 속성에서 지정한 메서 드가 호출  스프링은 빈 객체를 생성하고, 태그에 명시된 프로퍼티의 값을 설정한 뒤 빈 클래스가 구현한 인터페이스에 따라 위 그림에 명시한 순서대로 메서드를 호출  생성이 완료되면 BeanFactory.getBean() 메서드를 이용하여 빈 객체를 사용할 수 있 음

19 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

3

Life Cycle (cont’d)

• ApplicationContext

를 이 용할 경우

BeanFactory

라이프 사이클과 비교하여 몇 가지 단계가 추가 의

공 자원 및 이벤트 처리

,

이벤 트 처리 등 추가적인 기능 제 20 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

6

Event

ApplicationContext는 publishEvent()를 이용하여 객체를 전달 받을 수 있게 함

    ContextRefreshEvent ContextCloseEvent ContextStartedEvent(2.5) ContextStoppedEvet(2.5)

21 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

7

Annotation-based Setup

@Required

 필수 프로퍼티 검사, 인식은 스프링 설정파일과 함께 해야 어노테이션 인식함 

@Autowired

 의존관계를 자동으로 설정 (멤버 필드에도 적용 가능) 

@Qualifier

 자동 설정 제한, 자동 연결될 빈 객체의 수식어를 값Qualifier(“main”)으로 가짐 

@Resource

 의존하는 빈 객체 전달시 사용  네임 속성 사용 

@PostConstruct & @PreDestory

 라이프 사이클의 초기화 및 제거 과정 시작,끝 점 

위 어노테이션들은 특정 클래스에 설정 태그로 빈 객체를 등록해줘야 함 22 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

7

Annotation-based Setup (cont’d)

@Autowired 어노테이션을 이용한 자동 설정

  생성자, 필드, 메서드 세곳에 적용 가능 프로퍼티 자동 설정 기능 제공  Sender프로퍼티에 MessageSender타입의 빈 객체를 전달 public class SystemMonitor{ ...

@Autowired public void setSender(MessageSender sender){ this.sender = sender; } } ------------------------------------------------

nPstProcessor”/> <- 스프링 설정파일에 빈 객체로 등록하면 자동설정 적용됨

23 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

8

Component Scan

클래스 패스에 위치한 클래스를 검색

특정한 어노테이션이 기재된 클래스를 자동으로 빈으로 등록

XML 설정 없이 특정 클래스를 빈으로 등록 가능

@Repository

@Component

@Service

@Controller

ApplicationContext context = …; SystemMonitor monitor = (SystemMonitor)context.getBean(“systemMonitor”); --------- @Component(“monitor”) public class SystemMonitor {…}

24 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

8

Component Scan

스캔대상 범위 지정

   필터 태그 사용

25 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

8

Component Scan

Annotation 속성

 클래스에 지정한 어노테이션이 적용되었는지의 여부. Expression 속성에는 “org.example.SomeAnnotation”와 같이 어노테이션 이름을 입력 

Assignable 속성

 클래스가 지정한 타입으로 할당 가능 여부, expression속성에는 org.example.SomeClass 와 같ㄷ이 타입 이름을 입력 

Regex 속성

 클래스 이름이 정규 표현식에 매칭되는지의 여부. Expression 속성에는 org\.example\.Default.*와 같이 정규 표현식을 입력 

Aspectj 속성 26 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

ex

Spring Container DI 제거

27 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

28 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

29 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

30 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

31 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

8 32 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

33 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

34 / 2009 Spring Study – DJ Park, EH Jang, Shannon Lim

Thank you

본 컨텐츠는 NHN의 재산이므로 사전 동의 없는 도용이나 사용을 금합니다