공부기록

스프링 기본 설정하는 법 feat. Spring5, MyBatis, Eclipse 본문

Spring

스프링 기본 설정하는 법 feat. Spring5, MyBatis, Eclipse

gracelove91 2019. 11. 3. 18:04
반응형

본 프로젝트는 Spring 5.1.6 , MyBatis , MySQL 등으로 진행될 예정입니다.

sts설치부터 mybatis설정까지.

sts 설치.


https://spring.io/tools3/sts/all 에 들어가서 본인의 운영체제에 맞게 다운로드한 뒤 압축을 풀어줍니다.

(sts4는 스프링부트에 특화된 툴이기 때문에 sts3를 설치해야합니다.

후에 어떤 오류가 생길지도 모르니, 설치경로에 한글이 없게합니다.)

롬복플러그인 설치

 

 

https://projectlombok.org/download
다운로드를 마친 뒤, 롬복 플러그인이 다운로드 되어있는 폴더에 가서 명령프롬프트를 통해java -jar lombok.jar명령어를 실행시켜 설치합니다.

톰캣 8.5 설치


https://tomcat.apache.org/download-80.cgi 에서 톰캣 8.5.47 버전을 다운로드 받습니다. ( Core zip )
적당한 위치에 압축을 풀어줍니다. (추후 발생할 수 있는 오류를 막기 위해 설치경로에 한글이 없도록 합니다.)

mysql, mysql workbench 설치.


https://dev.mysql.com/downloads/mysql/ 에서 본인의 운영체제에 맞게, 버전은 5.7.28로 설치합니다. 설치과정 중 workbench를 설치하지않았다면,
https://dev.mysql.com/downloads/workbench/ 로 들어가 workbench 또한 설치합니다

스프링 레거시 프로젝트 시작.

 

sts 열어주신 뒤,
New -> Spring Legacy Project -> Spring MVC Project 선택
적절한 프로젝트 이름을 적어주신 뒤 Next 버튼을 눌러줍니다 ( 저는 exercise 로 했습니다. )
패키지 이름을 명시해줍니다. 패키지 이름은 웹사이트 이름을 거꾸로 적는 게 관례입니다. (저는 me.example.app 으로 했습니다.)

pom.xml

<properties>
        <java-version>1.8</java-version>
        <org.springframework-version>5.1.6.RELEASE</org.springframework-version>
        <org.aspectj-version>1.6.10</org.aspectj-version>
        <org.slf4j-version>1.6.6</org.slf4j-version>
</properties>

java-version을 1.8로 변경, org.springframework-version 을 5.1.6.RELEASE로 변경.

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

log4j 버전을 1.2.17로 변경.

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <scope>provided</scope>
        </dependency>

서블릿버전을 3.1로 변경. jsp버전을 2.3.3으로 변경.

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <compilerArgument>-Xlint:all</compilerArgument>
                    <showWarnings>true</showWarnings>
                    <showDeprecation>true</showDeprecation>
                </configuration>
            </plugin>

<source> 와 <target> 을 1.8로 변경.

                <!-- MyBatis. -->   
                <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
                <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

mybatis와 mybatis-spring 라이브러리 추가.

        <!--  HIKARICP -->
        <!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.4.1</version>
        </dependency>

hikariCP 라이브러리 추가.

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>

MySql 연결을 위한 라이브러리 추가.

                <!--  lombok -->
                <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>

롬복 라이브러리 추가.

        <!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>

SQL로깅을 위한 라이브러리 추가.

        <!-- Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

junit 버전을 4.12로 변경.

완성된 pom.xml

아티펙트아이디와 그룹아이디가 다를 수 있으니, 필요한 부분만 가져가시면 됩니다.

<?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>me.example</groupId>
    <artifactId>app</artifactId>
    <name>exercise</name>
    <packaging>war</packaging>
    <version>1.0.0-BUILD-SNAPSHOT</version>

    <properties>
        <java-version>1.8</java-version>
        <org.springframework-version>5.1.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>
        <!-- 스프링 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework-version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework-version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</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>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j-version}</version> 
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
            <!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4.1 -->
        <dependency>
            <groupId>org.bgee.log4jdbc-log4j2</groupId>
            <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
            <version>1.16</version>
        </dependency>

        <!-- @Inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <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.12</version>
            <scope>test</scope>
        </dependency>

                <!-- MyBatis. -->   
                <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
                <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

        <!--  HIKARICP -->
        <!-- https://mvnrepository.com/artifact/com.zaxxer/HikariCP -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>3.4.1</version>
        </dependency>

                <!--  lombok -->
                <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
            <scope>provided</scope>
        </dependency>


    <!-- mysql -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </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>1.8</source>
                    <target>1.8</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>

데이터베이스 연결.

root-context.xml 에 다음과 같은 설정을 추가합니다.

    <bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="driverClassName" value="net.sf.log4jdbc.sql.jdbcapi.DriverSpy"/>
        <property name="jdbcUrl" value="jdbc:log4jdbc:mysql://localhost:3306/[DB이름]"/>
        <property name="username" value="[username]"/>
        <property name="password" value="[password]"/>
    </bean>

    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
        <constructor-arg ref="hikariConfig"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

SQL 로깅을 위한 설정


src/main/resources/하위에 log4jdbc.log4j2.properties' 란 이름으로 파일을 생성해줍니다. 생성한 파일안에 다음과 같은 내용을 적습니다.log4jdbc.spylogdelegator.name=net.sf.log4jdbc.log.slf4j.Slf4jSpyLogDelegator`

mybatis 적용


src/main/java/..../mapper 패키지를 생성하고, interface SampleMapper를 생성합니다.

SampleMapper.java 내용

package me.example.app.mapper;

public interface SampleMapper {

    String getTime();

}

SampleMapper.xml


src/main/resourcesMapper.java 의 패키지에 맞춰 폴더를 생성해주고 xml파일을 만들어줍니다.
(SampleMapper.java의 패키지가 me.example.app.mapper.SampleMapper.java라면, xml파일 또한 src/main/resources 하위 me/example/app/mapper/SampleMapper.xml 위치시킵니다.)

SampleMapper.xml의 내용은 다음과 같습니다.

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="me.example.app.mapper.SampleMapper">

    <select id="getTime" resultType="string">
    SELECT now() from DUAL
    </select>

</mapper>

test작성

mybatis 설정과 HikariCP설정이 제대로 됐는 지 확인하기 위해 src/test/java/패키지이름 하위에 테스트코드를 작성합니다.
내용은 다음과 같습니다.

package me.example.app;

import javax.sql.DataSource;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import me.example.app.mapper.SampleMapper;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/main/webapp/WEB-INF/spring/root-context.xml")
public class DataSourceTest {

    private static final Logger log =  LoggerFactory.getLogger(DataSourceTest.class);

    @Autowired
    private DataSource dataSource;

    @Autowired
    private SampleMapper sampleMapper;

    @Test
    public void test() {
        log.info(dataSource.toString());
    }

    @Test
    public void testGetTime() {
        log.info(sampleMapper.getTime());
    }

}
반응형

'Spring' 카테고리의 다른 글

SPRING VALIDATOR  (0) 2019.11.13
java config으로 하는 Spring 셋팅.  (0) 2019.11.08
[Spring]비즈니스 인터페이스에서 의존성을 정의하지 말라.  (0) 2019.10.26
@PathVariable  (0) 2019.10.20
@RequestMapping의 value 패턴.  (0) 2019.10.19