[Spring] 싱글톤 패턴

    1. 싱글톤 패턴(Singleton Pattern)

    • 생성자가 여러 차례 호출되더라도 실제로 생성되는 객체는 하나이고, 최초 생성 이후에 호출된 생성자는 최초 생성자가 생성한 객체를 리턴함

    App.ctx

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class AppCtx {
    
    	@Bean 
    	public Client client() {
    		return new Client();
    	}
    }

     

    ClientMain.class

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.annotation.AnnotationConfigApplicationContext;
    
    public class ClientMain {
    
    	public static void main(String[] args) {
    		ApplicationContext ctx = new AnnotationConfigApplicationContext(AppCtx.class);
    		
    		Client c1 = ctx.getBean(Client.class);
    		Client c2 = ctx.getBean(Client.class);
    		
    		System.out.println("c1 == c2 ==> " + (c1 == c2));			// true
    		
    		Client c3 = new Client();
    		Client c4 = new Client();
    		
    		System.out.println("c3 == c3 ==> " + (c3 == c4));			// false
    	}
    
    }
    • 일반적으로 객체를 새로 생성할 경우(c3와 c4) 서로 다른 객체를 생성함
    • 싱글톤 객체의 경우(c1과 c2) 같은 객체를 리턴함

    'Spring' 카테고리의 다른 글

    [Spring] Swagger 라이브러리  (0) 2023.04.06
    [Spring] MVC 패턴  (0) 2023.04.05
    [SpringBoot] REST API란?  (0) 2023.04.05
    [Spring] 빌드 관리 도구  (0) 2023.04.04
    스프링(Spring), 스프링부트(SpringBoot)란?  (0) 2023.04.04

    댓글