250x250
Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags more
Archives
Today
Total
관리 메뉴

개린이 개발노트

[Spring] 스프링 빈(bean) 객체 생성하는 법 본문

스프링Spring

[Spring] 스프링 빈(bean) 객체 생성하는 법

개린이9999 2023. 1. 7. 23:41
728x90
class: 객체를 생성하기 위해 사용할 클래스를 지정한다.

id: Bean 객체를 가져오기 위해 사용하는 이름을 저장한다.

lazy-init: 싱글톤인 경우 xml을 로딩할 때 객체 생성 여부를 설정한다. true: xml로딩 시 객체를 생성하지 않고 객체를 가져올 때 생성한다.

scope: 객체의 범위를 설정한다.
slingeton: 객체를 하나만 생성해서 사용
prototype: 객체를 가져올 때 마다 객체를 생성한다.
package sanghoon.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import sanghoon.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext ctx= new  ClassPathXmlApplicationContext("sanghoon/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 객체의 주소값을 받아온다. 
		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 객체의 주소값을 받아온다.
		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();
	}
}
package sanghoon.beans;

public class TestBean {
	
	public TestBean() {
		System.out.println("TestBean의 생성자");
	}
}
<?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"> 

		<!--  xml을 로딩할 때 자동으로 객체가 생성된다. -->
	  	<bean class = 'sanghoon.beans.TestBean'/>
	  	
	  	<!-- xml을 로딩할 때 자동으로 객체가 생성됨 -->
	  	<!-- id 속성에 이름을 부여하면 getBean 메서드를 통해 객체의 주소값을 받아 사용할 수 있다. -->
	  	<!-- 생성된 객체는 더이상 생성되지 않는다.싱글톤 -->
	 	
	 	<bean id='test1' class = 'sanghoon.beans.TestBean'/>
	 	
	 	<!-- lazt-init:true - xml을 로딩할 때 객체가 생성안됨(생략하면false) -->
	 	<!-- getBean 메서드를 호출할 때 객체가 생성되며 singleton이기 때문에 객체는 하나만 생성된다. -->
	 	<bean id ='test2' class = 'sanghoon.beans.TestBean' lazy-init="true"/>
	 	
	 	<!--scope:prototype - xml을 로딩할 때 객체가 생성되지않는다.-->
	 	<!--getBean 메서드를 호출할 때 마다 새로운 객체를 생성해서 반환한다. -->
	 	<bean id ='test3' class = 'sanghoon.beans.TestBean' scope='prototype'/>
</beans>

 

Spring 에서는 프로그램에서 사용할 객체를 bean configuration 파일에 정의하여 사용

728x90