Spring practice_240617

Choi Suyeon·2024년 6월 17일

Spring DI

DAO : interface에서는 DB작업 목록만 기술.(구현 클래스에서 구현)
Service : interface에서는 업무목록만을 기술.(구현 클래스에서 구현)
Assembly : Service에서 어떤 DAO를 사용할지를 결정하고, DAO를 생성하고 Service에 의존성을 주입하는 코드를 구현.
Use : Assembly를 생성하고 의존성을 주입받는 service객체를 얻어, Service객체가 제공하는 기능을 사용(Controller).

Spring DI(약결합)

의존성을 주입하고, 의존성 주입받을 객체를 찾고 얻기 위해 Spring Container를 사용.
실행하기 위해 별도의 Container가 필요하지 않는다.
//Container : Servlet/JSP는 실행하기 위한 Container인 WAS필요.

Spring Container

빈의 라이프사이클(생성, 사용, 소멸)을 관리, 환경설정, 의존성 주입, 환경설정파일(XML)을 로드하고 관리하는 일.
BeanFactory, ApplicationContext, WebApplicationContext를 제공.

BeanFactory : 의존성주입, Bean생명주기 관리 => 핵심기능만 제공하는 Container
<
ApplicationContext : 일반 application의 의존성주입, Bean생명주기 관리, 국제화, 파일관리의 지원, 추상화
<
WebApplicationContext : Web Application의 의존성 주입, Bean생명주기 관리, 국제화, 파일관리의 지원, 추상화

Bean

Spring Container가 객체를 생성하고, 생명주기를 관리하는 대상클래스를 지칭하는 용어.
설정파일에 등록되거나, annotation으로 사용할 수 있다.
bean은 Spring Container에서 Singleton방식으로 하나의 객체만 생성되고 사용.
(요청할 때마다 생성하고 싶으면 설정파일에서 scope="prototype"으로 설정하여 사용.)

  • 사용법
1. 설정파일(applicationContext.xml)에 bean등록.(등록된 클래스는 싱글턴 객체로 생성된다.)
1-1. 의존성 주입할 클래스를 설정
<bean id="객체명" class="패키지명.클래스명" scope="singleton" /\>
<bean id="od" class="day0617.OracleDAO" scope="singleton" /\>
  
1-2. 의존성 주입받을 클래스설정하고, 의존성 주입.
<bean id="객체명" class="패키지명.클래스명" scope="singleton"\>
  <constructor-arg ref="od"/\>
</bean\>
  
2. Spring Container로 부터 Bean얻기
  Service service = ac.getBean(의존성주입받은 클래스명.class);

  • Spring Container에서 bean생성
    <bean id="객체명" class="패키지명.class명" scope="singleton"/>
    scope속성은 getBean으로 객체를 꺼낼때마다 생성하는 prototype 속성값과 하나의 객체만 만들고 사용하는 singleton속성을 사용할 수 있다.
  • bean으로 등록된 객체들은 Spring Container가 생성하고, 찾아서 반환한다.
  • 문법
ApplicationContext ac = new ClassPathXmlApplicationContext({"설정파일",,,});
  
spring 2.5.3이하) - 권장하지 않는다.
  클래스명 객체명 = (Casting)ac.getBean("찾아낼 객체의 id");
  
spring 2.5.3이상)
  클래스명 객체명 = ac.getBean(클래스명.class);//패키지명.클래스명.class
  
* 에러)
같은 이름의 클래스가 다른 id로 등록되어 있을 때에는 error가 발생한다.
  
<bean id="test1" class="day0617.Test" scope="singleton"/>
<bean id="test2" class="day0617.Test" scope="singleton"/>
  
ac.getBean(Test.class);
//입력되는 class에 해당하는 class를 찾기 때문에 여러 개의 bean이 검색되므로 error 발생.
ac.getBean("아이디", 클래스명.class);

0개의 댓글