티스토리 뷰

Inversion of Control(IoC)

: The approach of outsourcing the construction and management of object.

객체의 건설과 관리를 직접하지 않고 외주를 맡기는 것이다. 

간단히 말해서 나의 application이 객체의 생성과 관리를 아웃소싱 맡기는 것이고, 그 아웃소싱이 object factory에 의해 조절되는 것이다.

 

예를들어 보자면, 

Coding Scenario

1. App이 설정가능해야한다.(configurable)

2. Coach가 baseball coach만이 아닌 어떠한 다른 코치로도 쉽게 바뀔수 있어야 한다.

(여기서Myapp.java는 main method가 있는 메인프로그램, coach.java는 refactoring을 한 후의 인터페이스, BaseballCoach.java는 coach.java를 implement한것)

 

예제 1) BaseballCoach.java를 만들어 MyApp.java에서 실행한다.

package com.luv2code.springdemo;

public class MyApp {

	public static void main(String[] args) {
		// create the object
		BaseballCoach theCoach = new BaseballCoach();
		// use the object
		System.out.println(theCoach.getDailyWorkout());
	}

}
package com.luv2code.springdemo;

public class BaseballCoach{
	
	public String getDailyWorkout() {
		return "Spend 30 minutes on batting practice";
	}
}

여기서의 문제점 : Baseball 코치뿐만 아니라 다른 코치로 쉽게 변하지 못한다. 

→ Coach들은 모두 getDailyWorkout() 메소드가 있기때문에 인터페이스로 만들어준다.(software engineering 관습이다)

package com.luv2code.springdemo;

public interface Coach {
	public String getDailyWorkout();
}
package com.luv2code.springdemo;

public class BaseballCoach implements Coach{
	
	@Override
	public String getDailyWorkout() {
		return "Spend 30 minutes on batting practice";
	}
}
package com.luv2code.springdemo;

public class MyApp {

	public static void main(String[] args) {
		// create the object
		Coach theCoach = new BaseballCoach();
		// use the object
		System.out.println(theCoach.getDailyWorkout());
	}
}
package com.luv2code.springdemo;

public class TrackCoach implements Coach {
	
	@Override
	public String getDailyWorkout() {
		return "Run a hard 5k";
	}
}

다음과 같이 Coach 인터페이스를 만들고, 각 코치 객체를 implement해서 사용하여 MyApp.java에서 생성하는 객체의 종류에 따라서 비교적 쉽게 다른 코치객체로 변경 가능하다. 위와같이 Coach를 implement한 TrackCoach객체를 만들어서 MyApp.java에서 BaseballCoach를 TrackCoach로 변경할수 있다.

→ 2번 문제는 해결했지만 app이 configurable해야한다는 문제가 남았다. 위 코드는 여전히 hard coded된 상태이다. java코드를 변경하지 않고 외부의 configuration file 변경을 통해 쉽게 전환되었으면 좋겠다. 정확히 이문제를 spring으로 해결한다.

 

Spring Inversion of Control Overview

스프링 컨테이너(Object Factory의 역할)의 주요 기능

  1.  객체의 생성과 관리(Inversion of Control)
  2.  객체에 의존성 주입(Dependency Injection)

스프링 컨테이너를 configuring하는 법

  1.  XML Configuration File (legacy, 스프링이 출시되었을때 부터 써왔고 여전히 legacy app을 쓰고 있다.)
  2.  Java Annotation (현대방식, 가장 최근의 방식)
  3.  Java Source Code (현대방식)

Spring 개발 과정(Development Process)

  1.  configure Spring beans(XML, annotation, source code를 이용해서)
  2.  spring container 생성 (spring container는 ApplicationContext로 알려져 있다.)
  3.  spring container로 부터 Bean 회수
<?xml ../>
<beans ..>
    </bean>
    <!-- Define your beans here -->
   
    </bean>
    <bean id="myCoach" 
    class="com.luv2code.springdemo.TrackCoach">
    </bean>
</beans>
package com.luv2code.springdemo;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloSpringApp {

	public static void main(String[] args) {

		// load the spring configuration file
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		// retrieve bean from spring container
		Coach theCoach = context.getBean("myCoach", Coach.class);

		// call methods on the bean
		System.out.println(theCoach.getDailyWorkout());
		
		// close the context
		context.close();
	}
}

(xml 파일에서 bean id는 그저 가명으로 이름을 하나 붙혀준것이고, class에는 자격있는 implementation class를 적어준다. App에서 bean을 회수하는 과정의 getBean 메소드에 의해서 연결된다.( getBean(bean id, 인터페이스명.class))

Step 1. Configure Spring beans에서 configuration file로 xml을 예시로 들었다.

Step 2. Spring container를 생성하여 configuration file을 넘겨준다. 

Step 3. Spring container에서 생성된 bean들을 회수한다.

 

다음과 같이 xml configuration file을 간단히 변경하는것 만으로, App의 자바 코드를 건들지 않고 기능을 할수 있다. 이처럼 스프링을 이용하여 app은 configurable하며, xml configuration file을 변경함으로서 쉽게 다른 코치로 변경가능하다. 

 

 

최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday