티스토리 뷰

반응형


Spring은 초기 설정이 정말 중요한 만큼..

나중을 위해 기록을 해두자.!


묵시적 DI 방법을 바탕으로 작성했다.

여기서 사용되는 annotation을 먼저 살펴보자.


@Component 

=> Class를 Bean으로 등록


@Configuration 

=> 환경 설정 파일이라는 것을 명시


@ComponentScan("com.cristoval.web.book") 

=> @Compoment어노테이션 및 streotype(@Service, @Repository, @Controller.) annotation 부여된 Class들을 

   자동으로 Scan하여 Bean으로 등록


@Autowired 

=> 각 상황의 타입에 맞는 IoC컨테이너 안에 존재하는 Bean을 자동으로 주입









| 프로젝트 생성



> Spring Legacy Project



> Spring MVC Project



> package

package는 3-level로 작성해주어야 한다.

보통 웹 사이트는 com.company.app 으로 3-level이 만들어지게 되어있다.

package level은 com.{도메인}.{프로젝트명} 이라고 생각하면 된다.

예를 들어 Cristoval 회사(cristoval.com)에서의 web 프로젝트다! 라고 한다면

com.cristoval.web 으로 package를 생성해주면 된다.








| pom.xml 수정



버전을 확인하고, 변경하기 위해서는

pom.xml 파일 수정이 필요하다.


<properties> 태그에서

java, maven, springframework 등 버전 설정이 가능하다.


JavaSE-1.8 version

spring 5.2.6 version 을 사용할 것이다.

<maven.compiler.source>1.8</maven.compiler.source>

<maven.compiler.target>1.8</maven.compiler.target>


<org.springframework-version>5.2.6.RELEASE</org.springframework-version>


<dependencies> 태그에는

maven repository 에서 제공하는 <dependency>를 세팅할 수 있다.


/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
<?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>
    <groupId>com.cristoval</groupId>
    <artifactId>web</artifactId>
    <name>1021_HW</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <org.springframework-version>5.2.6.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
    </properties>
    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</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>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</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.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
 
        </plugins>
    </build>
</project>
 
cs



pom.xml 파일을 수정한 후 저장하면, 버전이 적용된다. (시간이 다소 걸릴 수도 있다.)

단, maven은 프로젝트 우클릭 -> Maven -> Update Project 를 해줘야 적용이 된다.








| xml to Java



xml 파일을 Java 파일로 변경할 것이다.

수정해야 할 xml 파일은

root-context.xml 과 servlet-context.xml


그 전에 먼저, web.xml 을 확인해보자.


line 7~9) /WEB-INF/spring/root-context.xml 에서는 백엔드 관련 동작을 수행하고

line 18~26) /WEB-INF/spring/appServlet/servlet-context.xml 에서는 웹과 관련된 동작을 수행한다.

line 33~45) 마지막 단계에 설명이 있지만 미리 해둬도 된다. encoding 설정!


/src/main/webapp/WEB-INF/web.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
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
 
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
        
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
        </init-param>
     </filter>
     
     <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>
 
</web-app>
 
cs



||| root-context.xml



root-context.xml 에는 공유자원을 등록


[ BEFORE ]

backend Bean 설정을 위해 아래와 같이 설정했다면

1
<context:component-scan base-package="com.cristoval.web.model"></context:component-scan>
cs


[ AFTER ]

1.

Java Config 파일을 만든 후,

환경 설정 파일이라는 것을 명시하기 위해 @Configuration annotation 을 작성하고,

Bean의 위치를 명시하는 @ComponentScan annotation을 작성해주어야 한다.


src/main/java/com/cristoval/web/config/ApplicationConfig.java

1
2
3
4
5
6
7
8
9
10
11
package com.cristoval.web.config;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan("com.cristoval.web.model")
public class ApplicationConfig {
 
}
 
cs


2.

Java Config Bean을 인식할 수 있도록 context:annotaion-config 태그를 작성해줘야하는데,

작성을 위해 먼저 context configure 체크를 해야주어야 한다.


src/main/webapp/WEB-INF/spring/root-context.xml


context:annotaion-config 태그를 작성한 후,

Java Config 기반 설정을 Bean으로 등록해준다.

이제 ApplicationConfig는 com.cristoval.web.config.ApplicationConfig를 참조하게 된다.


src/main/webapp/WEB-INF/spring/root-context.xml

1
2
3
4
5
<!-- Java Config Bean을 인식하도록. -->
<context:annotation-config></context:annotation-config>
 
<!-- Java config 기반 설정을 Bean으로 등록 -->
<bean name="rootConfig" class="com.cristoval.web.config.ApplicationConfig"></bean>
cs



전체 코드


src/main/java/com/cristoval/web/config/ApplicationConfig.java 전체 코드

1
2
3
4
5
6
7
8
9
10
package com.cristoval.web.config;
 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
 
@Configuration
@ComponentScan("com.cristoval.web.model")
public class ApplicationConfig {
 
}
cs


src/main/webapp/WEB-INF/spring/root-context.xml 전체 코드

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    
    <!-- Root Context: defines shared resources visible to all other web components -->
    <context:annotation-config></context:annotation-config>
    <bean name="rootConfig" class="com.cristoval.web.config.ApplicationConfig"></bean>
</beans>
cs




||| servlet-context.xml



servlet-context.xml 에는 웹 관련 config 작성


BEFORE ]


src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
 
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
 
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
 
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>
 
<context:component-scan base-package="com.cristoval.web" />
cs



[ AFTER ]

1.

Java Config 파일을 만든 후,

환경 설정 파일이라는 것을 명시하기 위해 @Configuration annotation 을 작성하고,

Bean의 위치를 명시하는 @ComponentScan annotation을 작성해주어야 한다.

또한 WebMvcConfigurer interface 를 implemets 하고,

@EnableWebMvc annotation 을 작성해준다.


src/main/java/com/cristoval/web/config/MVCConfig.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
@Configuration
// <annotation-driven />
@EnableWebMvc
// <context:component-scan base-package="com.cristoval.web" />
@ComponentScan("com.cristoval.web.controller")
public class MVCComfig implements WebMvcConfigurer {
    
    /* 정적 리소스 위치 등록
    <resources mapping="/resources/**" location="/resources/" />
    */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/res/**"// 화면에서 요청하는 리소스 위치
                .addResourceLocations("/resources/"// 실제로 그 리소스들이 있는 물리적 경로
                .setCachePeriod(60 * 60 * 24 * 365); // cache로 남겨둘 기간 설정
        
    }
     
    /* 라이브러리의 클래스를 빈으로 써야한다. 
     * --> 소스를 편집할 수 없으므로 @Conponent 설정 불가
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
     */
    @Bean
    public InternalResourceViewResolver viewRoseolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
}
cs


2.

다음으로 root-context.xml 수정 방법과 같이

context:annotaion-config 태그를 작성한 후,

Java Config 기반 설정을 Bean으로 등록해준다.

이제 Java Config는 com.cristoval.web.config.MVCConfig를 참조하게 된다.


src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml

1
2
<context:annotation-config></context:annotation-config>
<beans:bean id="mvcconfig" class="com.cristoval.web.config.MVCComfig"></beans:bean>
cs



전체 코드


src/main/java/com/cristoval/web/config/MVCConfig.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
37
38
39
40
41
42
43
44
45
package com.cristoval.web.config;
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
 
@Configuration
// <annotation-driven />
@EnableWebMvc
// <context:component-scan base-package="com.cristoval.web" />
@ComponentScan("com.cristoval.web.controller")
public class MVCComfig implements WebMvcConfigurer {
    
    /* 정적 리소스 위치 등록
    <resources mapping="/resources/**" location="/resources/" />
    */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/res/**"// 화면에서 요청하는 리소스 위치(사용자)
                .addResourceLocations("/resources/"// 실제로 그 리소스들이 있는 물리적 경로
                .setCachePeriod(60 * 60 * 24 * 365); // cache로 남겨둘 기간 설정
        
    }
     
    /* 라이브러리의 클래스를 빈으로 써야한다. 
     * --> 소스를 편집할 수 없으므로 @Conponent 설정 불가
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
     */
    @Bean
    public InternalResourceViewResolver viewRoseolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
    
}
 
cs


src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:annotation-config></context:annotation-config>
    <beans:bean id="mvcconfig" class="com.cristoval.web.config.MVCComfig"></beans:bean>
 
</beans:beans>
 
cs








| web.xml CharactorEncoding



한글 입력 시 깨지는 현상을 막기 위해 Encoding 설정도 해주어야 한다.


/src/main/webapp/WEB-INF/web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
<filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
 </filter>
 
 <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>
cs




***

Spring@MVC 프로젝트의 기본적인 세팅 방법이다.


세팅을 완료하였으니,

1. DTO

2. Repo

3. Service

4. JSP

5. Controller

를 작성해보자!



** 읽어보고 싶은 참고 글 **


반응형

'Web > Spring' 카테고리의 다른 글

[MyBatis] MyBatis Setting 을 해보자 !  (4) 2020.10.22
[Spring] Spring@MVC 구조 및 @annotation 살펴보기.  (0) 2020.10.21
[Spring] log4j.xml 로그 확인하기  (0) 2020.10.21
[Spring] Spring AOP  (0) 2019.09.22
[Spring] Spring-IoC, Bean, DI  (0) 2019.09.21
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday