spring 1

스프링 프레임워크

  • 공통 프로그래밍 모델 및 Configuration 모델을 제공
  • 애플리케이션 수준의 인프라 구조를 제공
  • 개발자가 귀찮은 일에 신경쓰지 않고 비즈니스 로직 개발에 전념


의존성

  • 객체생성의 의존성 => 생성 안 하면 됨. 관계의 역전
  • 타입의 의존성 => 느슨한 결합


IoC (Inversion Of Control)

  • 객체지향 언어에서 객체 간의 연결 관계를 런타임에 결정하게 하는 방법
  • 객체 간의 관계가 느슨하게 연결됨 (loose coupling)
  • IoC의 구현 방법 중 하나가 DI (Dependency Injection)


DI (Dependency Injection)

각 클래스간의 의존 관계를 빈(Bean) 설정 정보를 바탕으로 컨테이너가 자동으로 연결해주는 것


스프링 컨테이너가 객체생성 관리를 하는 방법

  1. xml

    1. 생성자 주입

      • spring bean configuration file 생성

      • <bean class="클래스" id="보통 클래스명에서 맨 앞글자 소문자로 하여 사용">
          <!-- 매개변수 설정. 생성자에 매개변수가 없다면 생략 가능 -->
        	<constructor-arg>
          	<ref bean="아이디2"/>
          </constructor-arg>
        </bean>
                
        <bean class="클래스2" id="아이디2" scope="prototype"></bean>
        
      • 클래스명 a = new 클래스(아이디2); 와 같은 의미를 지닌다

      • 클래스명2 b = new 클래스명2(); 와 같은 의미를 지닌다


    2. 설정자 주입

      • 클래스 생성자가 아닌 set 메서드 생성

      • spring bean configuration file 생성

      • public class 클래스 {
          private 클래스2 변수2;
          public void set클래스2(클래스2 파라미터) {
            this.변수명2 = 파라미터;
          }
        }
        
      • <bean class="클래스2" id="아이디2"></bean>
        <bean class="클래스" id="아이디">
        	<property name="클래스2" ref="아이디2"></property> <!-- setter 메서드 정의 -->
          <!-- setter 메서드 명을 name 속성으로 정의. setName의 경우 name으로 정의 -->
        </bean>
        
  2. 어노테이션 + 설정파일

    1. 생성자 주입

      • spring bean configuration file 생성 후 Namespaces에서 context 체크

      • <context:component-scan base-package=""></context:component-scan>
        
    2. 설정자 주입

      • 위와 동일


  3. 설정파일까지도 모두 자바로 처리

    • 설정파일로 쓸 자바 클래스 위에 @Configuration 선언

    • @Configuration
      public class ApplicationConfig {
        @Bean
        public ProductService productService() {
          ProductService productService = new ProductServiceImpl();
          return productService;
        }
      }
      
  • 어노테이션

    • @Configuration : 이 클래스는 설정파일임을 명시
    • @Bean : 관리할 객체를 명시, 메서드명이 빈 객체의 아이디가 된다
    • @Component : 스프링이 객체의 생성, 관리, 소멸을 담당하도록 선언. class 위에 선언
    • @Autowired : 해당 타입의 매개변수에 맞는 객체를 찾아서 주입해준다
    • @Qualifier : 같은 타입의 Bean 객체가 여러개 존재할 때 id를 지정해준다


  • 설정파일을 가져올 때

    • xml

      • ApplicationContext context = new GenericXmlApplicationContext(".xml");
        
    • java

      • ApplicationContext context = new AnnotationConfigApplicationContext(ApplicationConfig.class);