BACKEND/Spring

bean 객체 생성하기

죠으닝 2023. 10. 18. 14:40

 

testbean 생성

package com.demo.beans;

public class TestBean {

	public TestBean() {
		System.out.println("테스트빈 생성자");
	}
}

 

 

beans.xml 에서 새로 만든 클래스 등록

	<!-- 해당 클래스로 만든 객체 hello를 스프링에 등록 -->
	<!-- <bean id="hello" class="com.demo.beans.HelloWorldEn" /> -->
	<bean id="hello" class="com.demo.beans.HelloWorldKo" />
	<bean id="t1" class="com.demo.beans.TestBean" />

 

 

 

main

 

 

package com.demo.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.demo.beans.HelloWorld;
import com.demo.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
		// beans.xml 파일을 로딩한다
		ClassPathXmlApplicationContext ctx = 
				new ClassPathXmlApplicationContext("com/demo/config/beans.xml");
		
		//xml에 정의된 beans 객체의 주소값을 가져온다. 
		//bean 이름이 hello임 (id값) 타입은 object로 리턴되기 때문에 타입 설정이 필요함 
		//그래서 (HelloWorld) 붙여줌 
		
		//타입 설정 첫 번째 방법
//		HelloWorld hello1 = (HelloWorld)ctx.getBean("hello");
//		callMethod(hello1);
//		
//		
//		//타입 설정 두 번째 방법
//		HelloWorld hello2 = ctx.getBean("hello",HelloWorld.class);	
//		callMethod(hello2);
		
		
		TestBean t1 = ctx.getBean("t1",TestBean.class);
		System.out.printf("t1: %s\n",t1);
		
		TestBean t2 = ctx.getBean("t1",TestBean.class);
		System.out.printf("t1: %s\n",t2);
		
		
		
		ctx.close();

	}
	
	
	public static void callMethod(HelloWorld hello) {
		hello.sayHello();
	}

}

 

 

 

14:06:07.727 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64
14:06:07.869 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 2 bean definitions from class path resource [com/demo/config/beans.xml]
14:06:07.890 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'hello'
14:06:07.899 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 't1'
테스트빈 생성자
t1: com.demo.beans.TestBean@49c7b90e
t1: com.demo.beans.TestBean@49c7b90e
14:06:07.921 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:06:07 KST 2023

객체는 한번만 만들어지고 , 주소는 동일하다. 

 

 

 

 

 

 

 

 

 

pom.xml 복사 후 업데이트하면 설정은 끝남 

 

 

 

 

패키지도 복사해서 붙여넣기

 

 

 

 

안의 내용들은 다 제거하기

 

 

ctrl + shift + o 하면 안쓰는 import 제거 

 

 

 

 

 

 

 

 

TestBean 클래스 생성

 

 

package com.demo.beans;

public class TestBean {
	public TestBean() {
		System.out.println("테스트빈 생성자");
	}
}

 

 

 

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">

	<!--xml로딩 시 자동 객체 생성 id 즉 이름이 없음. -->
	<bean class='com.demo.beans.TestBean' />

	<!--xml로딩 시 자동 객체 생성 이름있음 기본 싱글턴 -->
	<!-- 이름은 test1, main에서 getbean을 통해서 주소값을 받아 사용이 가능함 -->
	<bean id="test1" class='com.demo.beans.TestBean' />

	<!-- 이름 test2 기본 싱글턴, lazy-init으로 가져올 때 객체생성 -->
         <!-- 생성이 된 객체는 더 이상 생성되지 않음. -->
	<!-- lazy-init : true = xml을 로딩할 때 객체가 생성되지 않음.  -->    
	<bean id="test2" lazy-init="true" class='com.demo.beans.TestBean' />

	<!-- 이름은 test3, main에서 getbean을 통해서 주소값을 받아 사용이 가능함 -->
	<!-- 생성이 된 객체는 더 이상 생성되지 않음. -->
	<!-- scope: prototype = xml을 로딩할 때 객체가 생성되지 않고,
          getbean메서드 호출할 때 마다 새로운 객체 생성 후 반환 -->
	<bean id="test3" scope="prototype" class='com.demo.beans.TestBean' />

</beans>

 

 

main에서 확인하기 


t1,t2 -test1

 

t1

package com.demo.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.demo.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
		// beans.xml 파일을 로딩한다
		ClassPathXmlApplicationContext ctx = 
				new ClassPathXmlApplicationContext("com/demo/config/beans.xml");
	
		TestBean t1 = ctx.getBean("test1",TestBean.class);
		System.out.printf("t1 : %s\n",t1);
		
		ctx.close();

	}
	
}

결과 확인 - 테스트빈이 두 번 생성됨 

 

첫 번째 빈은 이름이 없어서 생성됨 ''com.demo.beans.TestBean#0'

두 번째 빈 생성  'test1'

 

14:29:56.535 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64
14:29:56.680 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 4 bean definitions from class path resource [com/demo/config/beans.xml]
14:29:56.701 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'com.demo.beans.TestBean#0'
테스트빈 생성자
14:29:56.710 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'test1'
테스트빈 생성자
t1 : com.demo.beans.TestBean@6f46426d
14:29:56.732 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:29:56 KST 2023

 

 

t2

package com.demo.main;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.demo.beans.TestBean;

public class MainClass {

	public static void main(String[] args) {
		// beans.xml 파일을 로딩한다
		ClassPathXmlApplicationContext ctx = 
				new ClassPathXmlApplicationContext("com/demo/config/beans.xml");
	
		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);
		
		
		ctx.close();

	}
	
}

결과확인 

14:32:43.722 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64
14:32:43.865 [main] DEBUG org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loaded 4 bean definitions from class path resource [com/demo/config/beans.xml]
14:32:43.885 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'com.demo.beans.TestBean#0'
테스트빈 생성자
14:32:43.893 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'test1'
테스트빈 생성자

t1 : com.demo.beans.TestBean@6f46426d //같은 객체 주소임
t2 : com.demo.beans.TestBean@6f46426d //같은 객체 주소임
14:32:43.915 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:32:43 KST 2023

t2를 만들 때는 이미 t1에서 생성한 객체가 있어서 

더 이상 생성되지 않음. 

 

 

 

 


t3 , t4- test2

 

<!-- 이름있음 기본 싱글턴, lazy-init으로 가져올 때 객체 생성 -->

 

lazy-init="true" 

 

생략하면 false임

	
		// 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);

 

 

객체는 한 번만 만들어지고 주소는 같

14:34:44.888 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'test2'
테스트빈 생성자
t3 : com.demo.beans.TestBean@49c7b90e
t4 : com.demo.beans.TestBean@49c7b90e
14:34:44.892 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:34:44 KST 2023

 

 

 

 

 


t5 , t6- test3

 

scope='prototype'

xml 로딩 시 객체 생성되지 않음. 

메소드가 호출 될 때마다 새로운 객체를 생성함 

 

 

		// id가 test3인 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);

결과 확인 - 주소가 다름 가져올 때마다 새 객체를 생성해서 

테스트빈 생성자
t5 : com.demo.beans.TestBean@10d307f1
테스트빈 생성자
t6 : com.demo.beans.TestBean@4d5b6aac
14:36:10.773 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Closing org.springframework.context.support.ClassPathXmlApplicationContext@32d2fa64, started on Wed Oct 18 14:36:10 KST 2023

 

 

개념만 이해하자