본문 바로가기
웹 프로그래밍(풀스택-->java)/웹프로그래밍(백엔드-->java)

52. 빈 객체 생성하기

by 백엔드개발자0107 2021. 12. 19.

우리가 지난 시간에는 IOC컨테이너 개념에 대해서 살펴보았다.

 

이번시간에는 IOC컨테이너를 통해서 빈 객체를 만드는 방법을 알아볼것이다

 


Spring Bean 객체 생성

  • 스프링에서는 사용할 Bean 객체를 Bean configuration file 에 정의를 하고 필요할 때 객체를 가져와 사용하는 방법을 이용한다.
  • Bean 태그 : 사용할 Bean을 정의하는 태그



 

MainClass.java

 

package kr.co.softcampus.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import kr.co.softcampus.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
	
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
		
		//id 가 test1인 bean 객체의 주소값을 반환한다.
		TestBean t1 =ctx.getBean("test1",TestBean.class);
		System.out.printf("t1:%s\n",t1);
		
		TestBean t2 = ctx.getBean("test1",TestBean.class);
		System.out.printf("t2:%s\n",t2);
		
		//id가 test2인 bean객체의 주소값을 받아온다.("test2"의 같은 키 값이면 같은 주소값을 할당받는다)//같은 싱글톤 객체를 반환한다.
		TestBean t3 = ctx.getBean("test2",TestBean.class);
		System.out.printf("t3:%s\n",t3);
		
		TestBean t4 = ctx.getBean("test2",TestBean.class);
		System.out.printf("t4:%s\n",t4);

		//id가 test3인 bean객체의 주소값을 받아온다.(scope:prototype)이기 때문에 새로운 객체를 계속 생성한다 . 
		TestBean t5  = ctx.getBean("test3",TestBean.class);
		System.out.printf("t5:%s\n",t5);
		
		TestBean t6 = ctx.getBean("test3",TestBean.class);
		System.out.printf("t6:%s\n",t6);
		
		
		
		ctx.close();
	}
}

TestBean.java

 

package kr.co.softcampus.beans;

public class TestBean {

	public TestBean() {
		
		System.out.println("TestBean의 생성자");
		
	}
	
	
}

beans.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="hello" class="kr.co.softcampus.beans.HelloWorldEn"/> -->
<!-- <bean id="hello" class="kr.co.softcampus.beans.HelloWorldKo"/> -->
<!-- xml을 오딜앟때 자동으로 객체가 생성된다. 그런데 우리가 생성된 객체의 주소값을 IOC컨테이너가 가진 객체의 주소값을 가지기 위해서는 id 가 필요하다. -->
<!-- 현재까지의 학습진도상 id 속성이 없다면 객체의 주소값을 받아서 사용할수 없다.  -->
<bean class="kr.co.softcampus.beans.TestBean"/>

<!-- xml을 로딩할때 자동으로 객체가 생성된다. -->
<!-- id 속성에 이름을 부여하면 getBean메소들를통해 객체의 주소값을 받아 사용할수있다.  -->
<!-- 생성된 객체는 더이상 생성되지 않는다. Singleton -->
<bean id="test1" class="kr.co.softcampus.beans.TestBean"/>


<!-- lazy-init : true - xml을 로딩할 떄 객체가 생성되지 않는다.(생략하면 false) -->
<!-- getBean메서드를 호출할때 객체가 생성되며 singleton(객체가 하나)이기 때문에 객체는 하나만 생성된다. -->
<bean id="test2" class="kr.co.softcampus.beans.TestBean" lazy-init="true"/>

<!-- scope : prototype - xml을로딩할때 객체가 생성되지 않는다. -->
<!-- getBean메소드를 호출할 때마다 새로운 객체를 생성해서 반환한다. -->
<bean class = "kr.co.softcampus.beans.TestBean" scope="prototype"/>




</beans>