Spring/Study 2020. 4. 7. 22:21

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

 

스프링(Spring)에서는 자바처럼 new를 이용하여 객체를 직접 생성하지 않고, 스프링 설정파일(XML)을 이용한다. 

 

스프링(Spring) 프로젝트 생성 : https://devmoomini.tistory.com/46

 

Hello.java

1
2
3
4
5
6
7
8
package helloSpring;
 
public class Hello {
    public void print() {
        System.out.println("Hello World!");
    }
}
 
cs

- Line 4 : print() 메소드 선언

- Line 5 : Hello World! 출력

 

applicationContext.xml

1
2
3
4
5
6
7
8
9
<?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="hello" class="helloSpring.Hello" />
 
</beans>
cs

- Line 7 : Hello 클래스를 hello라는 ID의 bean으로 등록

 

MainClass.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package helloSpring;
 
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainClass {
    public static void main(String[] args) {
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:applicationContext.xml");
        
        Hello hello = ctx.getBean("hello", Hello.class);
        hello.print();
        
        ctx.close();
    }
}
 
cs

- Line 7 : 스프링 컨테이너가 생성되고, 내부에 bean 객체들이 생성 (XML로부터 객체 설정 정보를 가져옴)

- Line 9 : hello라는 객체를 생성하고, XML에서 ID가 hello인 bean을 가져와서 넣어줌

- Line 10 : hello 객체의 print() 메소드 호출

- Line 12 : 스프링 컨테이너와 bean 객체들이 소멸

 

실행결과

posted by DevMoomin
: