코딩기록 저장소 🐕/spring(JPA)🌱

Spring 시작

kimkongmom 2023. 9. 25. 08:52

 

 

 

• IoC

 IoC, Inversion of Control
 제어의 역전
 개발자가 프로그램을 제어하지 않고, Framework가 프로그램을 제어하는 것을 의미함
 객체 생성, 의존관계 설정(Dependency), 생명주기(Lifecycle) 등을 Framework가 직접 관리하는 것을 말함

 

• IoC 컨테이너

 컨테이너(Container) : 객체의 생명주기를 관리하고 생성된 인스턴스를 관리함
 Spring Framework에서 객체를 생성과 소멸을 담당하고 의존성을 관리하는 컨테이너를 IoC 컨테이너라고 함
 IoC 컨테이너 = 스프링 컨테이너

 

 

 

 

 

• <property> 태그
 Setter를 이용해서 값을 전달하고 저장함
 작성방법-1
<property name="필드">
<value>값</value>
</property>
 작성방법-2
<property name="필드" value="값" />

 

주의!
참조 타입의 값을 저장할 때는 value가 아닌 ref 속성을 사용해야 함

 

• <constructor-arg> 태그
 Constructor를 이용해서 값을 전달하고 저장함
 작성방법-1
<constructor-arg>
<value>값</value>
</constructor-arg>
 작성방법-2
<constructor-arg value="값" />

 

 

 

 

 

 

 

 

Maven

 

1. Maven 레파지토리  https://mvnrepository.com/에 각종 jar 파일을 보관하고 있다.

2. pom.xml 파일에 등록된 <dependency> 태그에 의해서 jar 파일이 작동으로 다운로드 된다.
      3. pom.xml 파일을 수정하면 다운로드로 연결되므로 자주 저장하지 않는 것이 좋다.
      4. 다운로드 받은 jar 파일들은 C:\Users\사용자\.m2\repository 디렉터리에 저장된다.
      5. jar 파일에 문제가 발생한 경우 
        1) STS를 끈다.
        2) C:\Users\사용자\.m2\repository 디렉터리를 지운다.
        3) 다시 STS를 켠다.
        4) 새로 다운로드 될 때까지 기다린다.
        5) 프로젝트 우클릭 - [Maven] - [Update Project]

 

 

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
  
    <!-- top level package, artifactId는 contextPath가 된다. -->
    <groupId>com.gdu</groupId>
    <artifactId>app01</artifactId>
  
    <!-- 프로젝트 이름 -->
    <name>01_IoC</name>
    <!-- deploy(배포) file -->
    <packaging>war</packaging>
  
    <!-- 프로젝트 버전 -->
    <version>1.0.0-BUILD-SNAPSHOT</version>
  
    <!-- 
      속성의 버전에 따른 디펜던시(jar)를 다운로드 받는다.
      작성된 버전 사용방법
      ${java-version} -> 11으로 변경된다.
      ${org.springframework-version} -> 5.3.3으로 변경된다.
      ${org.aspectj-version} -> 1.9.6으로 변경된다.
      ${org.slf4j-version} -> 1.7.30으로 변경된다.
      
      springframework 버전 : 2021sus 01월 버전
      org.aspectj, org.slf4j 버전은 springframework 버전과 맞추거나 이전 버전을 사용
     -->
    <properties>
        <java-version>11</java-version>
        <org.springframework-version>5.3.3</org.springframework-version>
        <org.aspectj-version>1.9.6</org.aspectj-version>
        <org.slf4j-version>1.7.30</org.slf4j-version>
    </properties>
  
    <!-- 디펜던시 : 필요한 jar 파일을 자동으로 가져온다. -->
    <dependencies>
  
    <!-- https://mvnrepository.com/artifact/com.oracle.database.jdbc/ojdbc8 -->
    <dependency>
        <groupId>com.oracle.database.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <version>23.2.0.0</version>
    </dependency>
    
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework-version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                 </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
                
        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${org.aspectj-version}</version>
        </dependency>    
        
        <!-- Logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${org.slf4j-version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.15</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.mail</groupId>
                    <artifactId>mail</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>javax.jms</groupId>
                    <artifactId>jms</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>runtime</scope>
        </dependency>
 
        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
                
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    
        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>      
      
    </dependencies>
  
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <additionalProjectnatures>
                        <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                    </additionalProjectnatures>
                    <additionalBuildcommands>
                        <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                    </additionalBuildcommands>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>true</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>${java-version}</source>
                    <target>${java-version}</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <version>1.2.1</version>
                <configuration>
                    <mainClass>org.test.int1.Main</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
 
cs

 

 

XML 구성 파일은 Spring Framework를 사용하여 빈을 정의하고 의존성 주입을 설정하는 간단한 예제

Person과 Calculator class 정의

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.gdu.app01.xml01;
 
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
 
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Person {
  private String name;
  private int age;
  private Calculator calculator;
  
}
 
cs

 

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
package com.gdu.app01.xml01;
 
 
public class Calculator {
  
  // no field
  
  // default constructor : new Calculator()
  
  // method
  public void add(int a, int b) {
    System.out.println(a + "+" + b + "=" + (a + b));
  }
  public void sub(int a, int b) {
    System.out.println(a + "-" + b + "=" + (a - b));
  }
  public void mul(int a, int b) {
    System.out.println(a + "X" + b + "=" + (a * b));
  }
  public void div(int a, int b) {
    System.out.println(a + "/" + b + "=" + (a / b));
  }
  
 
}
 
cs

 

Main 실행 

 

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
51
52
package com.gdu.app01.xml01;
 
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
 
public class MainWrapper {
  
  public static void ex01() {
    
    // app-context.xml 파일 읽기(여기에서 <bean> 태그로 정의해 둔 객체가 생성된다.)
    AbstractApplicationContext ctx = new GenericXmlApplicationContext("xml01/app-context.xml");
    
    // <bean> 태그로 정의된 객체 가져오기
    Calculator calculator = (Calculator)ctx.getBean("calc"); // ctx.getBean("calc", Calculator.class) 코드로 동일함
    
    // 객체 사용해 보기
    calculator.add(12);
    calculator.sub(34);
    calculator.mul(56);
    calculator.div(78);
    
    // app-context.xml 파일닫기
    ctx.close();
  }
 
  public static void ex02() {
    
    // app-context.xml 파일 읽어서 <bean> 태그로 정의된 객체 만들기
    AbstractApplicationContext ctx = new ClassPathXmlApplicationContext("xml01/app-context.xml");
    
    // 객체 가져오기(man, woman)
    Person man = (Person)ctx.getBean("man");
    Person woman = ctx.getBean("woman", Person.class);
    
    // 객체 확인
    System.out.println(man.getName() + "," + man.getAge());
    man.getCalculator().add(12);
    System.out.println(woman.getName() + "," + woman.getAge());
    woman.getCalculator().add(25);
    
    // app-context.xml 파일 닫기
    ctx.close();
  }
  
  public static void main(String[] args) {
    ex02();
   
  }
 
}
 
cs

 

 

app-context.xml

 

<bean> 요소를 사용하여 Calculator, man, woman 빈을 정의합니다.
Calculator 빈은 singleton 스코프로 정의되어 있으며, 클래스 이름과 아이디(id)를 설정합니다.
man 빈은 setter 메서드를 사용하여 name, age, calculator 프로퍼티를 설정합니다. 이때 ref 속성을 사용하여 calculator 프로퍼티에 Calculator 빈을 주입합니다.
woman 빈은 생성자를 이용하여 name, age, calculator 프로퍼티를 설정합니다. 역시 ref 속성을 사용하여 Calculator 빈을 주입합니다.

 

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
<?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">
 
  <!-- Calculator calc = new Calculator(); -->
  <bean class="com.gdu.app01.xml01.Calculator" id="calc" scope="singleton"/>
  <!-- 
    1. 디폴트 생성자 + setter 
      Person man = new Person();
      man.setName("뽀로로");
      man.setAge(20);
      man.setCalculator(calc);
   -->
   <bean class="com.gdu.app01.xml01.Person" id="man">
     <property name="name" value="뽀로로"/>
     <property name="age" value="20"/>
     <property name="calculator" ref="calc"/>
   </bean>
   
   <!-- 
     2. 필드를 이용한 생성자
       Person woman = new Person("루피", 20, calc);
    -->
    <bean class="com.gdu.app01.xml01.Person" id="woman">
      <constructor-arg value="루피"/>
      <constructor-arg value="20"/>
      <constructor-arg ref="calc"/>
    </bean>
</beans>
 
cs