새소식

인기 검색어

개인공부/SPRING

spring 입문

  • -

 

public class Greeter {
    private String format;

    public String greet(String guest) {//입력받은 문자열을 포맷설정으로 반환
        return String.format(format, guest);
    }

    public void setFormat(String format) {//문자열 포맷 설정
        this.format = format;
    }
}

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration//해당 클래스를 스프링 설정 클래로 지정하는 어노테이션이다
public class AppContext {

    @Bean//@Bean을 붙인 메서드는 해당 메서드가 생성한 객체를 스프링이 관리하는 빈 객체로 등록한다 이떄 생성한 객체는 메서드의 이름을 따라간다
    //빈 객체란 스프링이 생성하는 객체를 뜻한다.
    public Greeter greeter() {
        Greeter g = new Greeter();
        g.setFormat("%s,안녕하세요!");
        return g;
    }
}
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
//AnnotationConfigApplicationContext 클래스는 자바 설정에서 정보를 읽어와 빈 객체를 생성하고 관리
public class Main {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx =
                new AnnotationConfigApplicationContext(AppContext.class);
        //AnnotationConfigApplicationContext 는 파라미터로 받은 AppContext클래스에서 @Bean으로 설정한 메서드내의 Greeter객체를 생성하고 초기화
        Greeter g1 = ctx.getBean("greeter", Greeter.class);
        Greeter g2 = ctx.getBean("greeter", Greeter.class);
        //getBean()는 AnnotationConfigApplicationContext가 생성한 빈 객체를 검색할떄 사용된다.
        //getBean()의 첫번째 파라미터는 빈 객체의 이름이면 두번쨰 파라미터는 검색할 빈 객체의 타입이다.
        System.out.println("(g1 == g2) = " + (g1 == g2));//(g1 == g2) = true
        ctx.close();
    }
}

📌추가설명

더보기

간단한 스프링 프로그램인 Main을 작성하고 실행해봤다.

이 코드의 핵심은 AnnotationConfigApplicationContext클래스이다.

AnnotationConfigApplicationContext은 자바 애노테이션을 이용하여 클래스로부터 객체 설정 정보를 가져와 객체 생성과 초기화를 수행하는 클래스이다.

 

 그리고 별도 설정을 하지 않을 경우 스프링은 기본적으로  한 개의 빈객체를 생성하기에 기본적으로 빈 객체는 싱글톤 객체이다. 따라서 g1 == g2로 같은 객체인것을 확인 할 수 있다.

 

 

'개인공부 > SPRING' 카테고리의 다른 글

@Bean vs @Component 차이  (1) 2022.10.08
Lombok이란? 및 Lombok 활용법  (0) 2022.10.06
어노테이션(@, annotation)의 정의와 종류  (0) 2022.10.06
MAVEN이란?  (0) 2022.10.06
IntelliJ Spring 프로젝트 생성  (0) 2022.10.06
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.