프로그래밍 기초/SPRING
[Spring]스프링의 사용 1 -스프링을 사용하는 이유
jejeb
2020. 1. 28. 10:42
스프링을 사용하는 이유 :
핵심 의존타입을 스프링에 맡기고 인터페이스를 적극적으로 활용하여 개발 시 의존관계를 완화하기 위하여 스프링을 사용한다.
스프링 사용하지 않을 때 와 사용할 때 의 비교
attack메소드를 가지고 있는 인터페이스 Weapon이 있고
Weapon을 implements하는 TestWeapon이 있다고 가정해보자.
이 때 스프링을 사용할 때와 스프링을 사용하지 않을 때롤 비교해 보겠다.
package test.example;
import test.mypac.TestWeapon;
import test.mypac.Weapon;
public class MainClass {
public static void main(String[] args) {
//useWeapon()메소드를 호출하는게 목적이라면?
//필요한 type객체를 직접 생성해서
TestWeapon w2=new TestWeapon();
//메소드를 호출함으로써 목적을 달성한다.
useWeapon(w2);
}
//Weapon(인터페이스) type을 전달해야 호출할 수 있는메소드
public static void useWeapon(Weapon w) {
w.attack();
}
}
↑스프링을 사용하지 않는경우 :
1. MainClass에서 객체를 new해서 직접 생성한다.
2.import 부분에 TestWeapon이 있다.
package test.example2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test.mypac.Weapon;
public class MainClass {
public static void main(String[] args) {
//init.xml문서를 해석해서 bean 을 생성한다.
ApplicationContext context=
new ClassPathXmlApplicationContext("test/example2/init.xml");
//스프링이 관리하고 있는 객체중에서 "myWeapon"이라는 이름의 객체의
//참조값을 가지고 와서 Weapon type으로 casting해서 변수에 담는다.
Weapon w1=(Weapon)context.getBean("myWeapon");
//Weapon type 객체를 이용해서 원하는 동작을 한다.
useWeapon(w1);
}
public static void useWeapon(Weapon w) {
w.attack();
}
}
<?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">
<!-- WeaponImpl 객체를 생성하고 그 객체의 이름을 myWeapon으로 부여한다. -->
<bean id="myWeapon" class="test.mypac.TestWeapon"/>
</beans>
↑스프링을 사용하는경우 :
1. 객체를 MainClass에서 직접 new하지 않고 xml문서에서 TestWeapon 객체를 생성한다.
xml에서 생성한 객체를 getBean으로 가져와서 변수에 담아 사용한다.
2. WeaponImpl을 import하지 않아도 사용할 수 있다.
스프링을 사용하지 않을 경우에는 TestWeapon 을 import하기 때문에 TestWeapon이름을 변경시오류가난다.
스프링 사용 시 TestWeapon 을 import하지 않아도 되기 때문에 TestWeapon이름을 변경하더라도 오류가 나지 않는다.
이것이 스프링의 사용이 의존관계를 완화한다는 것의 의미이다.