반응형

Spring - Hello World Example


(원문 : http://www.tutorialspoint.com/spring/spring_hello_world_example.htm )


모두의 'Hello World'를 한번 만들어보자.

원문에서는 일반 Java Project를 생성해서 관련 Spring library를 추가하는 방식으로 진행하고 있으나, 

추후 AOP관련 부분에서 이와같은 방식으로 프로그램이 수행되지 않아서 (내가 뭘 잘못해서 그런건지 아직도 모르겠지만...) AOP도 잘 돌아가는 Maven을 이용하여 Spring project를 생성하여 진행한다.


Step 1 - Create Java Project:

    - File -> New -> Spring Project
      : Project Name : 01.HelloWorld


프로젝트를 생성하면 아래와 같은 구조를 갖게 된다.


Step 2 - Create Source Files:

이제 소스를 추가해보자.
패키지명은 원문과 같이 "com.tutorialspoint" 로 한고 아래 파일을 그림과 같은 구조로 추가한다.
- HelloWorld.java
- MainApp.java
- Beans.xml


 HelloWorld.java file:

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }

   public void getMessage(){
      System.out.println("Your Message : " + message);
   }
}


 MainApp.java:

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");

      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

      obj.getMessage();
   }
}

    - main program에서 두가지 중요한 점이 있다.

      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml"); 

: Framework API인 ClassPathXmlApplicationContext를 사용하여 application context를 생성하는 단계이다. 이 API는 Bean 설정 파일을 로드하고 결국은 제공되어지는 API에 근거하여 설정파일에서 언급된 모든 bean 객체를 생성하고 초기화한다..    


      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

: 생성된 context의 getBean() 함수를 사용하여 사용하려는 bean을 가지고 오는 단계이다. 이 함수는 결국은 실제 객제초 캐스팅되어지는 generic object를 가져오기 위해 bean ID를 사용한다. 일단 객체를 가져오면, 객체의 어떠한 함수도 사용할 수 있다.


Beans.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-3.0.xsd">

   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>
: Bean에 대해서는 이후 다시 언급할 예정이다. 여기서는 간단하게 보자
  주의깊게 볼 부분은 아래부분이다. 나머지는 COPY & PASTE 해도 무방할 것이다.
   <bean id="helloWorld" class="com.tutorialspoint.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

  <bean> 태그로 bean을 선언하는 부분으로 id 속성이 getBean()에 사용된 이름임을 알 수 있다.  class 속성은 실제 class가 선언된 패키지와 클래스명임을 알 수 있다. 즉, 'helloWorld'를 getBean()으로 호출하면 실제 'com.tutorialspoint.HelloWorld' 클래스와 연결되는 것이다. <property> 태그 등은 이후 다시 언급된다.

              

Step 3 - Running the Program:

결과 : Your Message : Hello World!


반응형

+ Recent posts