ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 6장 bean 객체 생성하기
    스프링 프레임워크 기초 공부 2020. 4. 26. 20:47

    bean 태그의 기본 속성

     

    class : 객체를 생성하기 위해 사용할 클래스를 지정한다.

     

    id : Bean 객체의 주소값 가져오기 위해 객체의 이름을 지정한다.

     

    lazy-init : 싱글톤인 경우 xml을 로딩할 때 객체 생성 여부를 설정한다.

                 설정에 true추가: xml 로딩 시 객체를 생성하지 않고 객체를 가져올 때 생성한다.

     

    scope : 객체의 범위를 설정한다.

                설정에 singleton추가: 객체를 하나만 생성해서 사용한다.

                설정에 prototype: 객체를 가져올 때 마다 객체를 생성한다.

     

    bean을 사용한 객체 생성

    package kr.co.softcampus.beans;
    
    public class TestBean {
    	public TestBean()
    	{
    		System.out.println("TestBean1의 생성자");
    	}
    }
    

                                                                    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">
    						
    						
    	<bean id = 'test1' class='kr.co.softcampus.beans.TestBean'/>
    </beans>

                                                                       pom.xml

     

    TestBean클래스를 객체화 함 id는 test1

     

    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) {
    		// TODO Auto-generated method stub
    		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
    		
    		TestBean t1 = ctx.getBean("test1",TestBean.class);
    		System.out.println("t1:"+t1);
    		
    		TestBean t2 = ctx.getBean("test1",TestBean.class);
    		System.out.println("t2:"+t2);
    		
    		ctx.close();//ioc컨테이너 해제 객체들 소멸됨
    	}
    
    }
    

                                                                    main class

     

    결과창

    TestBean1의 생성자
    t1:kr.co.softcampus.beans.TestBean@731f8236
    t2:kr.co.softcampus.beans.TestBean@731f8236   

     

    결과창을 보면 참조변수를 두개 만들어서 객체의 주소값을 출력해보았지만 같은 주소값이 나오는것을 볼 수 있다.

    이를 보면 객체가 한번 생성되면 더이상은 객체가 생성되지 않는것을 볼 수 있다 즉 둘다 같은 인스턴스 인 것이다.

    이것이 바로 singleton이다 

     

    다음으로 pom.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 = 'test1' class='kr.co.softcampus.beans.TestBean'/>
    	
    	<bean class='kr.co.softcampus.beans.TestBean'/> --> 추가됨
    	
    	
    </beans>

     

     

    결과창

    TestBean1의 생성자
    TestBean1의 생성자
    t1:kr.co.softcampus.beans.TestBean@731f8236
    t2:kr.co.softcampus.beans.TestBean@731f8236

     

    결과창을 보면 생성자가 하나더 생성되었다. 이를 java 형식으로 보면 new연산자를 통해 생성자가 한개 더 호출된거라고 볼 수 있다.

     

     

    ----------------------------------------------------------------------------------------------------------------------

     

     

    다음 생성한 객체의 id 를 test2로 주고 mainclass에서 주솟값을 받아와 참조변수에 넣어보았다.

     

    그런데 객체의 주소값이 새롭게 생성된것을 볼 수 있다. 이를 통해 새로운 인스턴스가 생성된걸 볼 수 있다.

     

     

    lazy-init

    lazy-init을 true로 주면 xml 로딩 시 객체를 생성하지 않고 객체를 가져올 때(getbean메소드사용할때) 생성한다.

     

    lazy-init사용x

    pom.xml을 보면 객체를 사용하겠다라고 두번 선언이 되있음 , 창 또한 생성자가 두번 실행된것을 볼 수 있다.

     

    lazy-init사용O

    pom.xml을 보면 두번째 객체 생성부분에서 lazy-init="true"가 추가된걸 볼 수 있으면 결과창 에서 생성자가 한번만 실행된것을 볼 수 있다. 

     

    이를 통해 lazy-init을 사용하지 않으면 xml을 로딩하는 순간 객체가 생성되고 lazy-init을 사용하면 getBean메소드를 사용해야 객체가 생성되는것을 알수있다.

     

    scope

    객체의 범위를 설정한다.

                설정에 singleton추가: 객체를 하나만 생성해서 사용한다.

                설정에 prototype: 객체를 가져올 때 마다(getbean할때마다) 객체를 생성한다.

     

     

    scope = prototype을 사용하니 객체의 주소값이 다르게 2번 생성됨

     

    scope=singleton을 사용하니 주소값이 같게 2번 생성됨 결국 같은 객체라는 소리이다

     

     

     

    bean객체의 생명주기

    bean객체의 생명주기는 ioc컨테이너가 종료되는 시점까지이다. 코드로 봤을때ctx.close()가 됬을때를 말한다

    추가적으로 spring에서는 xml파일에 속성을 추가하여 bean객체가 생성됬을때, 소멸됬을때 메소드를 호출시킬수있다.

     

    속성

    init-method:생성자 호출 이후 자동으로 호출된다.

    destroy-method:객체가 소멸될 때 자동으로 호출된다.

    default-init-method:init-method를 설정하지 않은 경우 자동으로 호출된다.

    default-destroy-method:destroy-method를 설정하지 않은 경우 자동으로 호출된다.

     

     

    bean객체 

    package kr.co.softcampus.beans;
    
    public class TestBean1 {
    	
    	public TestBean1() {
    		System.out.println("TestBean1의 생성자 입니다");
    	}
    	
    	public void bean1_init() {
    		System.out.println("TestBean1의 init 메서드");
    	}
    	
    	public void bean1_destroy() {
    		System.out.println("TestBean1의 destroy 메서드");
    	}
    }
    

    TestBean1클래스에 객체가 생성되었을때 실행할 메소드와 객체가 소멸됬을때 실행말 메소드를 2개 생성한다

     

    xml파일 설정

     

    <!-- 객체가 생성될 때 생성자가 호출된 이후 init-method에 설정한 메서드가 자동으로 호출되고 IoC 컨테이너의 close 메서드를 호출하면
    		객체가 소멸되며 destroy-method에 설정한 메서드가 자동으로 호출된다.
    	 -->
    	<bean id='t1' class='kr.co.softcampus.beans.TestBean1' lazy-init='true' init-method="bean1_init" destroy-method="bean1_destroy"/>

     

    ioc컨테이너가 xml파일 로딩

    public class MainClass {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
    	
    		TestBean1 t1 = ctx.getBean("t1", TestBean1.class);
    		System.out.printf("t1 : %s\n", t1);
            }
     }

     

    출력문

    TestBean1의 생성자 입니다

    TestBean1의 init 메서드

    TestBean1의 destroy 메서드

     

     

     

    다음으로 init과 destroy속성이 사용되지 않았을때 설정한 기본값을 호출하도록하는방법

     

    bean객체

    package kr.co.softcampus.beans;
    
    public class TestBean2 {
    	
    	public TestBean2() {
    		System.out.println("TestBean2의 생성자");
    	}
    	
    	public void default_init() {
    		System.out.println("TestBean2의 default_init");
    	}
    	
    	public void default_destroy() {
    		System.out.println("TestBean2의 default_destroy");
    	}
    }
    

     

    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"
    	default-init-method="default_init" default-destroy-method="default_destroy">
    	
        
    	<!-- init-method와 destroy-method가 설정되어 있지 않다면 default-init-method와 default-destroy-method에 설정되어 있는 메서드를 호출한다. -->
    	<bean id='t2' class='kr.co.softcampus.beans.TestBean2' lazy-init='true'/>
    	<!-- 만약 init-method, destroy-method와 default-init-method, default-destroy-method에 등록되어 있는 메서드가 모두 있을 경우
    		init-method, destroy-method에 설정되어 있는 메서드가 호출된다.
    	 -->

    namespace에 default-init-method="default_init" default-destroy-method="default_destroy" 를 추가

     

    ioc컨테이너가 xml파일 로딩

    package kr.co.softcampus.main;
    
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import kr.co.softcampus.beans.TestBean1;
    import kr.co.softcampus.beans.TestBean2;
    import kr.co.softcampus.beans.TestBean3;
    import kr.co.softcampus.beans.TestBean4;
    
    public class MainClass {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("kr/co/softcampus/config/beans.xml");
    
    		
    		TestBean2 t2 = ctx.getBean("t2", TestBean2.class);
    		System.out.printf("t2 : %s\n", t2);
            }
     }

     

    출력창

    TestBean2의 생성자

    TestBean2의 default_init

    TestBean2의 default_destroy

     

    만약 init-method, destroy-method와 default-init-method, default-destroy-method에 등록되어 있는 메서드가 모두 있을 경우


    init-method, destroy-method에 설정되어 있는 메서드가 호출된다.

     

     

     

     

Designed by Tistory.