본문 바로가기
개발관련/Spring

[Spring] 스프링은 어떻게 동작할까? (2) : 의존성 주입[xml방식]

by joa-yo 2019. 9. 27.
반응형

 

스프링에 의존성을 주입하는 방식은 두가지가 있다. XML파일을 사용하여 bean을 정의할 수 있고, class파일에 Annotation을 사용하여 주입할 수 있다. 처음에는 XML방식을 사용하여 의존성을 주입하다가, Annotation방식이 추가된 것으로 의존성주입의 기본이라 할 수 있는 XML방식으로 예제를 통해 의존성을 주입해보자.

<!-- 정리하기 --> 

의존성 주입 방식
  1. XML을 통한 bean 정의
    - 별도의 파일인 XML파일에 등록할 bean들을 모두 정의한다.
  2. Annoation을 통한 bean 등록
    - bean으로 등록할 객체의 Class파일에 Annotaion을 사용하여 bean으로 등록한다.

 

ApplicationContext와 BeanFactory가 무엇인지 모른다면? 이해가 어려우실 수도 있습니다. 확인 후 읽어주세요!

 

[Spring] 스프링은 어떻게 동작할까? (1)

spring은 무엇일까? 알고싶은데, 사용법만 설명하고 끝나는 경우가 많아 spring에서 제공하는 API, 그리고 자세히 설명되어 있는 블로그를 소개하며 SpringFrameWork가 어떤 것인지 낱낱이 살펴보려 한다. Spring..

joalog.tistory.com

 


의존성 주입

의존성 주입이란 무엇일까. A객체가 B객체를 필요하다고 하자. A객체는 B객체를 코드상에서 직접 생성하지 않고, BeanFactory가 생성하여 값 설정까지 모두 마친 뒤 B객체를 받아서 사용한다. 

Bean객체로 생성할 Triangle Class

public class Triangle implements Shape{
	private String type;
	private int height;
	
	public void draw(){
		System.out.println("draw shape:: triangle");
		System.out.println("detail shape :: " + getType());
		System.out.println("height :: " + getHeight());
	}
	//contructor-arg : 생성자를 통해 주입시 값을 설정.
	public Triangle(String type){
		this.type = type;
	}
	
	//contructor-arg : 생성자를 통해 주입시 값을 설정
	public Triangle(int height){
		this.type = type;
		this.height = height;
	}
	
	//contructor-arg : 생성자를 통해 주입시 값을 설정
	public Triangle(String type, int height){
		this.type = type;
		this.height = height;
	}
	

	//property : setter를 사용하여 멤버변수 값을 설정함.
	public void setType(String type){
		this.type = type;
	}
	
	public String getType(){
		return type;
	}
	
	//property : setter를 사용하여 멤버변수 값을 설정함.
	public void setHeight(int height){
		this.height = height;
	}
	
	public int getHeight(){
		return height;
	}
}

생성시에 값 초기화를 위환 생성자 몇가지와 getter, setter가 정의되어 있다. 모두 xml파일에서 값 주입시 사용되는 메소드이다. getter, setter는 모두 생성해주는 것이 좋으며, 생성자는 없을 경우 기본생성자가 사용되므로 필요한 경우 작성한다.

 


 

application을 실행할 Main Class

  public class Main {
	public static void main(String[] args) throws IOException {
1		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
2		Triangle triangle = (Triangle) (context.getBean("triangle"));
3		triangle.draw();
4		context.close();
    }
  }

1st line : ClassPathXmlApplicationContext라는 낯선 객체가 하나 보일 것이다. 이것은 ApplicationContext의 일종인데, ClassPath에 있는 파일을 사용하여 bean객체를 생성한다. 위에 정의되어 있는 "context.xml"은 src/main/resources 패키지에 있으며 파일명을 적는 것만으로 불러들일 수 있다. ApplicationContext 객체가 생성되면 bean객체들이 사용될 준비를 마치고 대기상태로 있는다

2nd line : bean id가 "triangle"인 객체를 가져온다. 이 때 객체는 Object 타입으로 오기 때문에 원래 객체 타입인 Triangle로 형변환을 하여 변수에 값을 넣는다.

3nd line : 가져온 객체를 사용한다.

4nd line : ApplicationContext의 사용을 종료한다. 이것을 적어주지 않으면 error문구가 떠서 적어주었다.

등록된 Bean을 사용하는 과정이다. 그렇다면, 어떻게 Bean을 설정할 수 있을까?

 


Bean으로 등록하기

 

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="triangle" class="com.tistory.joalog.Triangle"/>
</beans>

 

bean으로 등록 할 객체는 bean태그를 사용하여 정의한다. bean태그를 살펴보면 id속성이 보일 것이다. id는 getBean("[bean명칭]")메소드를 사용하여 객체를 불러들일 때 사용할 명칭을 정의한다. class속성은 등록할 객체의 위치를 정의하고 있는데, 패키지명칭과 클래스명을 나타내고 있다.

 

1. XML에서 멤버변수 값 설정하기

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="triangle" class="com.tistory.joalog.Triangle">
		<property name="type" value="Equilateral"></property>
	</bean>
</beans>

property태그를 사용하여 멤버변수 값을 정의할 수 있다. 멤버변수 이름은 name속성에, 그 값은 value에 설정해줄 수 있다. value값을 이용하여 설정할 수 있는 것은 String, int, boolean과 같은 기본형이다. 

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="triangle" class="com.tistory.joalog.Triangle">
		<property name="type" ref="point"></property>
	</bean>
    
	<bean id="triangle" class="com.tistory.joalog.Point" scope="ProtoType">
		<property name="x" value="0"></property>
		<property name="y" value="0"></property>
	</bean>
</beans>

 

참조형을 멤버변수로 설정하고 싶다면 ref속성를 사용하여 등록할 수 있다. 단 그 객체는 bean객체로 등록되어 있어야 하며 bean id를 적어주면 된다. 여기에서  Point의 scope속성을 ProtoType으로 지정해주었는데, 이렇게 설정하면 Triangle을 getBean()메소드를 사용하여 호출할 때 마다 새로운 Point객체가 생성된다. 멤버변수로 지정되는 경우에는, 대부분 ProtoType을 붙인다.

 

2. XML에서 생성자 사용하기

<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="triangle" class="com.tistory.joalog.Triangle">
		<constructor-arg value="Equilateral"></constructor-arg>
		<constructor-arg value="10"></constructor-arg>
	</bean>
</beans>

생성자를 통한값 지정은 contructor-arg를 사용하면 된다. 지정할 변수의 갯수만큼 지정해주면 자동적으로 갯수에 맞는 생성자를 선택하여 적용된다.

public Triangle(String type){
    this.type = type;
}

public Triangle(int height){
    this.type = type;
    this.height = height;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans>
	<bean id="triangle" class="com.tistory.joalog.Triangle">
		<constructor-arg type="int" value="10"></constructor-arg>
	</bean>
</beans>

생성자에 사용되는 변수 개수는 동일하고, 타입이 다른 생성자가 여러개 존재한다고 하자. 이러한 경우에는 타입을 정확하게 지정해주어야 하며 type속성을 사용해 변수의 타입을 설정할 수 있다.

 


XML로 의존성을 주입하는 기초적인 방법에 대해 알아보았다.   이 포스팅은 YouTube에 제공되는Java Brains의 Spring tutorial의 예제를 사용하여 작성한 포스팅으로 해당 내용을 공부하고나서 작성한 글입니다.

추가적인 설명이 필요하다면 댓글 부탁드립니다.

반응형

댓글