티스토리 뷰

※ 참고로 xml을 이용한 설정보다는 어노테이션을 사용하는 경우가 훨씬 더 많다.

 

Maven으로 자바프로젝트 만들기

 

· file → new → Maven Project

 

Archetype : maven-archetype-quickstart

프로젝트 명 : diexam01

 

pom.xml을 아래와 같이 수정

*pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>kr.or.connect</groupId>
  <artifactId>diexam01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
 
  <name>diexam01</name>
  <url>http://maven.apache.org</url>
 
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
  
-------------------------------------추가----------------------------------------------------
  <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
  </build>
----------------------------------------------------------------------------------------------
 
</project>
cs

 

그리고 저장을 하면 오류가 발생하는데,

프로젝트 오른쪽 클릭 → Maven → Update Project.. 를 클릭diexam01 선택 Ok를 누르면 오류가 사라진다.

 

후에 프로젝트 오른쪽 클릭 → Properties → Java Compiler 클릭 JDK 버전 1.8로 되어있는지 확인한다.

 

테스트하기

· src/test/java → kr.or.connect.diexam01 → AppTest.java

· Run As → JUnit Test

초록새 바가 뜨면 성공

 

DI 테스트 

- DI는 내가 원하는 객체를 내가 생성하는 것이 아니라 Spring이 제공하는 공장이 만들어서 주입시키는 것이다. 이 과정을 테스트 해볼 것.

- 공장이 자동으로 만들어주는 객체가 필요한데 그것을 bean이라고 부른다. 근래들어 일반적인 자바 클래스도 bean이라고 부른다.

Bean Class

- bean은 아래의 세가지 특성을 가지고 있어야 한다.

//필드는 private한다.
//기본생성자를 반드시 가지고 있어야 한다.
// setter getter 메서드를 가지고 있어야 한다. setter, getter메소드는 name프로퍼티라고 한다.(용어 중요)

 

*UserBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package kr.or.connect.diexam01;
 
public class UserBean {
    // 필드는 private한다.
    private String name;
    private int age;
    private boolean male;
    
    // 기본생성자를 반드시 가지고 있어야 한다.
    UserBean(){}
    UserBean(String name, int age, boolean male){
        this.name=name;
        this.age=age;
        this.male=male;
    }
    
    // setter getter 메서드를 가지고 있어야 한다. setter, getter메소드는 name프로퍼티라고 한다.(용어 중요)
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public boolean isMale() {
        return male;
    }
    public void setMale(boolean male) {
        this.male = male;
    }    
}
cs

 

이제 Spring 라이브러리를 추가한다.

 

구글 → maven spring context 검색
맨위 → 원하는 것선택하기, 우리는 Spring 4를 사용할 예정

 

*pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>kr.or.connect</groupId>
    <artifactId>diexam01</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>diexam01</name>
    <url>http://maven.apache.org</url>
    
    <!--추가된 영역, 상수를 선언하는 영역-->
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version> 4.3.18.RELEASE</spring.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
 
    <!--Spring 라이브러리 추가-->    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
 
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
 
cs

 

UserBean 설정하기

java/main  → resources 폴더 생성하기

resources → applicationContext.xml 파일 생성

 

applicationContext.xml에다 UserBean에 대한 설정들을 저장한다.

 

*applicationContext.xml

1
2
3
4
5
6
7
8
<?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="userBean" class="kr.or.connect.diexam01.UserBean"></bean>
 
</beans>
cs

 

bean 태그를 하나 입력했는데, 위의 태그는 다음과 같은 의미를 가진다.

UserBean userBean - new UserBean();

 

 

ApplicationContext를 이용해서 설정파일 읽어들여 실행하기

 

*ApplicationContextExam01.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package kr.or.connect.diexam01;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class ApplicationContextExam01 {
 
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");//매개변수는 아까 설정했던 공장 정보들을 전달한다.
        System.out.println("초기화 완료!");
        
        UserBean userBean = (UserBean)ac.getBean("userBean");
 
        userBean.setName("Kwon");
        System.out.println(userBean.getName());
        
        UserBean userBean2 = (UserBean)ac.getBean("userBean");
        
        if(userBean == userBean2) {
            System.out.println("같은 인스턴스입니다!");;
        }
    }
}
cs

 

- ApplicationContext인터페이스다.
- 그렇다는 것은 ApplicationContext를 구현하는 다양한 컨테이너가 존재한다는 뜻이다.
- 그 중 ClassPathXmlApplicationContext는 빈 정보가 담긴 xml파일을 읽어 들여, 이 안에 있는  bean(<bean>엘리먼트)을 생성해서 메모리로 올린다.
- 여러 개의 bean을 만들었다면(<bean>엘리먼트가 많다면) 그것들 전부 읽어들여 생성한뒤 메모리에 올린다, 이과정이 잘못되면 어플리케이션이 종료된다.

같은 인스턴스 판별

같은 인스턴스라고 나오는 이유 :
Spring ApplicationContext가 객체를 생성하는데, 사용자가 getBean()으로 요청을 한다 하더라도
그 객체들을 계속 만드는 것이 아니라 하나 만든 객체를 계속 이용하는 것이다.(싱글턴 패턴)

DI 실습

Engine.java

package kr.or.connect.diexam01;

public class Engine {
	public Engine() {
		System.out.println("Engine 생성자");
	}
	
	public void exec() {
		System.out.println("엔진이 동작합니다.");
	}
}

 

Car.java

package kr.or.connect.diexam01;

public class Car {
	Engine v8;
	
	public Car() {
		System.out.println("Car 생성자");
	}
	
	public void setEngine(Engine e) {
		this.v8 = e;
	}
	
	public void run() {
		System.out.println("엔진을 이용하여 달립니다.");
		v8.exec();
	}
}

위의 Car 클래스가 제대로 동작하도록 하려면 보통 다음과 같은 코드가 작성되야 합니다.

Engine e = new Engine();
Car c = new Car();
c.setEngine( e );
c.run();

1, 2 번째 줄을 Spring 컨테이너에게 맡기기 위해 설정파일에 다음과 같은 코드를 입력합니다.

<bean id="e" class="kr.or.connect.diexam01.Engine"></bean>
<bean id="car" class="kr.or.connect.diexam01.Car">
	<property name="engine" ref="e"></property>
</bean>

Car 객체는 Engine객체를 이용한다. Engine을 set하기 위해 property(getter,setter)를 사용.
설정을 하는 부분이기 때문에 setter 함수를 의미함.

즉, 위의 XML설정은 다음과 같은 의미를 가집니다.

Engine e = new Engine();
Car c = new Car();
c.setEngine( e );

이번엔 위의 설정 파일을 읽어들여 실행하는 ApplicationContextExam02.java를 작성해보도록 하겠습니다.

package kr.or.connect.diexam01;

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

public class ApplicationContextExam02 {

	public static void main(String[] args) {
		ApplicationContext ac = new ClassPathXmlApplicationContext( 
				"classpath:applicationContext.xml"); 

		Car car = (Car)ac.getBean("car");
		car.run();
		
	}
}

콘솔을 보면 다음과 같이 실행된 것을 알 수 있습니다.


참고 사이트 : http://www.edwith.org/



본 게시물은 개인적인 용도로 작성된 게시물입니다. 이후 포트폴리오로 사용될 정리 자료이니 불펌과 무단도용은 하지 말아주시고 개인 공부 목적으로만 이용해주시기 바랍니다.

' > 부스트코스' 카테고리의 다른 글

[Spring]Spring MVC  (0) 2018.08.02
[Spring]Spring JDBC  (1) 2018.08.01
[Spring]Spring IoC/DI 컨테이너  (0) 2018.07.31
[WEB]HTML Templating  (2) 2018.07.29
[WEB]이벤트 버블링과 이벤트 위임(Event Bubbling and Event Delegation)  (0) 2018.07.29
댓글