본문 바로가기

서버/Spring
[스프링(Spring)] DI, IoC

// IoC, Inversion of Control
- 역제어
- 제어의 권한이 프레임워크에 있다.
- 싱글톤으로 bean을 관리하는 일종의 Container

- 객체 생성 순서
   1. 기존 방식
      ~ BoardController > BoardService > BoardDAO
   2. 의존 주입
      ~ BoardDAO > BoardService > BoardController :: IoC


// DI, Dependency Injection


- DI : 디자인 패턴
- 스프링 기술 (X)
- 의존(성) 주입
- 인스턴스 생성 시 IoC Container에서 싱글톤으로 관리하는 bean들을 변수에 의존성 주입!
     > 어디에서 호출하여 사용하든 모두 같다(싱글톤)
- 스프링에서 중요한 개념 > 스프링의 모든 객체 관리에 사용
- 프로그래밍에서 구성 요소 간의 의존 관계가 소스 내부가 아닌 외부 환경에서 정의되게 하는 디자인 패턴

- 규모가 커지고, 유지보수 업무가 발생할 때는 DI를 이용한 개발의 장점을 느낄 수 있다.
    ~ Java 파일의 수정 없이 스프링 설정 파일만을 수정하여 부품들을 생성/조립할 수 있다. 


1. XML 방식

- XML에 정의된 <beans>를 통해서 객체를 관리한다.

- 스프링에서 관리하는 객체를 Spring Bean이라고 부른다.

* XML

<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
        				https://www.springframework.org/schema/beans/spring-beans.xsd">
        				
        				
    <!-- 
    	스프링이 관리하는 객체 :Spring Bean    	
    	Pen p1 = new Pen(); 
    -->
    <bean id="pen" class="com.test.di02.Pen"></bean>
    
    <!-- name: alias -->
    <bean id="brush" name="b1 b2 b3" class="com.test.di02.Brush"></bean>
    
    <bean id="hong" class="com.test.di02.Hong">
    	<!-- 스프링 의존 주입(DI) : Constructor -->
    	<constructor-arg ref="pen"></constructor-arg>
    </bean>
    
    <bean id="lee" class="com.test.di02.Lee">
    	<!-- 스프링 의존 주입 : Setter -->
    	<property name="brush" ref="brush"></property>
    </bean>
        				
</beans>
  • class : 패키지명 + 클래스명
  • property : setter를 통한 스프링 의존 주입
  • constructor-arg : constructor를 통한 스프링 의존 주입
  • ref : Spring Bean 매개변수

<bean id="myInfo" class="com.java.ex.MyInfo">
	<property name="name">
    	<value>홍길동</value>
    </property>
    <property name="height">
    	<value>187</value>
    </property>    
    <property name="weight">
    	<value>84</value>
    </property>    
    <property name="hobbys">
    	<list>
            <value>수영</value>
            <value>요리</value>
            <value>독서</value>
        </list>
    </property>
    <property name="bmiCaculator">
    	<ref bean="bmiCaculator"/>
    </property>
</bean>
  • value: 기초데이터
  • list value : List 타입
  • ref : 다른 빈객체 참조

* JAVA

ApplicationContext context = new ClassPathXmlApplicationContext("com/test/di02/di02.xml");
		
Pen p2 = (Pen)context.getBean("pen"); //id		
p2.write();
		
Brush b1 = (Brush)context.getBean("b1"); //name
b1.draw();
		
Brush b2 = (Brush)context.getBean("b2"); //name
b2.draw();
		
Brush b3 = (Brush)context.getBean("brush"); //name
b3.draw();

2. 어노테이션 방식

package com.test.di03;

import org.springframework.stereotype.Component;

@Component
public class Pen {
	
	public void write() {
		System.out.println("펜으로 글씨를 적습니다.");
	}

}

 

package com.test.di03;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class Hong {

	//4.
	@Autowired
	private Pen pen;
	
	//3. lombok
//	@Setter(onMethod_ = @Autowired)
//	private Pen pen;
	
	//1. 생성자
//	@Autowired
//	public Hong(Pen pen) {
//		this.pen = pen;
//	}
	
	
	//2. Setter
//	@Autowired
//	public void setPen(Pen pen) {
//		this.pen = pen;
//	}
	
	
	public void run() {
		pen.write();
	}
	
}
  •  @Component : <bean> 태그와 동일한 역할
          > 스프링이 관리하는 객체

 @Autowired : 의존주입 어노테이션
      > 아래에 있는 대상에 객체를 주입하라는 의미

'서버 > Spring' 카테고리의 다른 글

[스프링(Spring)] MVC 에러 처리  (0) 2023.06.16
[스프링(Spring)] MVC 데이터 수신 및 전송  (1) 2023.06.15
[스프링(Spring)] AOP  (1) 2023.06.15
[스프링(Spring)] JUnit  (0) 2023.06.14
[스프링(Spring)] 환경설정  (0) 2023.06.13