Spring 기본 프로젝트 생성

이주희·2022년 7월 21일
0

spring

목록 보기
2/16
  1. Greeter.java
    문자열 생성하는 평범한 클래스
package new2;

public class Greeter {
    private String format;

    public String greet(String guest){
        return String.format(format, guest);
        //두 문자열 합쳐짐
    }
    //새로운 문자열 생성

    public void setFormat(String format){
        this.format = format;
    }
     //format의 문자열 설정
}
  1. AppContext.java
    스프링이 생성하는 객체를 위의 클래스를 기반으로 생성
package new2;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

//Configuration -> 해당 클래스를 스프링 설정 클래스로 설정

@Configuration
public class AppContext{
    @Bean // 스프링이 생성하는 객체
    public Greeter greeter(){
        Greeter g = new Greeter();
        g.setFormat("%s, 안녕하세요!");
        return g;
    }

}
  1. Main.java
    위의 스프링 클래스를 이용한 프로그램 작성
package new2;

// 자바 설정에서 정보를 읽어와 빈 객체를 생성하고 관리
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {

    public static void main(String[] args){
        //앞에서 작성한 AppContext 클래스를 생성자 파라미터로 전달
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(AppContext.class);
        Greeter g = ctx.getBean("greeter",Greeter.class);
        String msg = g.greet("스프링");
        System.out.println(msg);
        ctx.close();
    }
}

0개의 댓글