Spring/Study 2020. 4. 9. 16:27

(공감과 댓글 하나는 글쓴이에게 큰 힘이 됩니다.)

 

싱글톤(Singleton)

스프링 컨테이너에서 생성된 빈(Bean) 객체의 경우 동일한 타입에 대해서는 기본적으로 한 개만 생성이 되며, getBean() 메소드로 호출될 때 동일한 객체가 반환된다. scope 속성을 명시하지 않으면 기본적으로 싱글톤으로 설정된다.

DependencyBean.java

package scope.ex;
 
public class DependencyBean {
    public DependencyBean() {
        System.out.println("DependencyBean : constructor");
    }
}
cs

applicationContext.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="dependencyBean" class="scope.ex.DependencyBean" />
    
</beans>
cs

MainClass.java

package scope.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
        
        DependencyBean dependencyBean1 = ctx.getBean("dependencyBean", DependencyBean.class);
        DependencyBean dependencyBean2 = ctx.getBean("dependencyBean", DependencyBean.class);
        
        if(dependencyBean1.equals(dependencyBean2)) System.out.println("dependencyBean1 == dependencyBean2");
        else System.out.println("dependencyBean1 != dependencyBean2");
        
        ctx.close();
    }
}
cs

실행결과

 

프로토타입(Prototype)

new로 객체를 생성할 때와 마찬가지로 getBean() 메소드로 호출할 때마다 매번 새로운 객체를 만든다. scope속성에서 protype이라고 명시를 해주어야 한다.

DependencyBean.java

package scope.ex;
 
public class DependencyBean {
    public DependencyBean() {
        System.out.println("DependencyBean : constructor");
    }
}
cs

applicationContext.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="dependencyBean" class="scope.ex.DependencyBean" scope="prototype" />
    
</beans>
cs

MainClass.java

package scope.ex;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
        
        DependencyBean dependencyBean1 = ctx.getBean("dependencyBean", DependencyBean.class);
        DependencyBean dependencyBean2 = ctx.getBean("dependencyBean", DependencyBean.class);
        
        if(dependencyBean1.equals(dependencyBean2)) System.out.println("dependencyBean1 == dependencyBean2");
        else System.out.println("dependencyBean1 != dependencyBean2");
        
        ctx.close();
    }
}
cs

실행결과

posted by DevMoomin
: