Spring IoC/DI 실습 2

Minkyeong Kim·2021년 11월 15일
0

[boostcourse] Web-Backend

목록 보기
24/55

Engine, Car 클래스 생성

  • Engine.java
package kr.or.connect.diexam01;

public class Engine {
	public Engine() {
		System.out.println("Engine 생성자");
	}
	
	public void exec() {
		System.out.println("엔진이 동작합니다.");
	}
}
  • Car.java
package kr.or.connect.diexam01;

public class Car {
	private Engine v8;
	public Car() {
		System.out.println("Car 생성자");
	}
	public void setEngine(Engine e) {
		this.v8=e;
	}
	public void run() {
		System.out.println("엔진을 이용하여 달립니다.");
		v8.exec();
	}
	public static void main(String[] args) {
		Engine e = new Engine();
		Car c= new Car();
		c.setEngine(e);
		c.run(); 
	}
}

Car 객체에서 Engine 객체를 사용하려면 미리 생성하여 set해야 함
-> ApplicationContext로 getBean을 하면 Car객체만 가져와도 따로 Engine 객체 생성할 필요 없이 실행됨

ApplicationContext.xml 파일 설정

<?xml version="1.0" encoding="UTF-8"?>
<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 http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="e" class="kr.or.connect.diexam01.Engine"></bean>
	<bean id="c" class="kr.or.connect.diexam01.Car">
		<property name="engine" ref="e"></property>
	</bean> 
</beans>

ApplicationContext 활용해 실습

package kr.or.connect.diexam01;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ApplicationContextExam02 {
	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
		// getBean는 Object형식으로 반환하므로 형변환 필수
		Car car=(Car) ac.getBean("c");
		car.run();
	}
}

0개의 댓글