이번에는 Spring Legacy Project로 Spring MVC Project를 생성했을 때, Resources 폴더에 등록하여 Junit5에서 태스트했을 때 사용하는 방법에 대해서 소개하려고 한다.
간단하지만, 의외로 처음 셋팅을 시도했을 때, 오류가 많이 생긴다.
글 제목에는 Beans가 적혀져 있지만, 따로 Beans 용어를 소개하진 않겠다.
이 코드를 해독하거나 태스트를 해 보면, Bean의 감을 잠시 맛볼 수는 있다.
* IDE: Eclipse 2020-06
* Framework: Spring Framework 4.2.4
* Spring-core
* Spring-tx
* Spring-jdbc
* Spring-test
* AspectJ
* AspectJWeaver
* 출력 결과
JUnit5와 Spring Framework 4.2.4 Releases의 조합으로 태스트를 하였다.
그림 1. 출력 결과 - 콘솔
그림 2. 태스트 결과
1. 프로젝트 구성도
아래의 그림은 프로젝트 구성도이다.
주로 작업할 코드는 "TestUnit.java", "applicationContext.xml", "db.properties", "pom.xml"이다.
그림 3. 프로젝트 구성도
2. Java Compiler, Build Paths, Project Factes
/src/main/webapp/WEB-INF/lib에 oracle JDBC.jar(ojdbc.jar) 파일 넣어주기
* Java Compiler - compiler compliance level 1.8
* Build Path - JUnit 5, JRE System Library (JavaSE 1.8) 등
- Add Jar로 ojdbc.jar 파일 등록해주기
* Project Factes - Java : 1.8
3. pom.xml
(중략)
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.4.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
(중략)
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- 밑줄 친 이유는 mvnrepository에서 찾아보면, scope라는 항목이 추가적으로 되어 있음. 지워야 동작함. -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AOP 구현할 경우에는 필요함. (AspectJ) -->
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${org.aspectj-version}</version>
<scope>runtime</scope>
</dependency>
4. db.properties(/src/main/resources)
jdbc.driver=org.h2.Driver
jdbc.url=jdbc:h2:tcp://localhost/~/test
jdbc.username=sa
jdbc.password=
MYSQL_DB_URL=jdbc:mysql://localhost:3306/dbanme?useUnicode=true&characterEncoding=utf8
MYSQL_DB_USERNAME=
MYSQL_DB_PASSWORD=
ORACLE_DB_URL=jdbc:oracle:thin:@127.0.0.1:1521:xe
ORACLE_DB_USERNAME=HR
ORACLE_DB_PASSWORD=1234
파일명: db.properties
[첨부(Attachments)]
5. applicationContext.xml(/src/main/resources)
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<context:component-scan base-package="com.website.example" />
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!-- DataSource 설정 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- DataSource 셋팅 -->
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="URL" value="${ORACLE_DB_URL}" />
<property name="user" value="${ORACLE_DB_USERNAME}"/>
<property name="password" value="${ORACLE_DB_PASSWORD}"/>
<property name="connectionCachingEnabled" value="true"/>
</bean>
<!-- Spring JDBC 설정 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- Transaction 설정 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:pointcut id="txPointcut" expression="execution(* com.website.example.service.DBService..*(..))"/>
<aop:advisor pointcut-ref="txPointcut" advice-ref="txAdvice"/>
</aop:config>
</beans>
파일명: applicationContext.xml
[첨부(Attachments)]
[추가]
<!-- MySQL - DataSource 셋팅 -->
<bean id="dataSource2" class="com.mysql.cj.jdbc.MysqlDataSource">
<property name="URL" value="${ORACLE_DB_URL}" />
<property name="user" value="${ORACLE_DB_USERNAME}"/>
<property name="password" value="${ORACLE_DB_PASSWORD}"/>
</bean>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> -->
<!-- 2. Oracle - DataSource 셋팅 -->
<bean id="dataSource" class="oracle.jdbc.pool.OracleDataSource" destroy-method="close">
<property name="URL" value="${ORACLE_DB_URL}" />
<property name="user" value="${ORACLE_DB_USERNAME}"/>
<property name="password" value="${ORACLE_DB_PASSWORD}"/>
<property name="connectionCachingEnabled" value="true"/>
</bean>
<!-- 3. Apache DBCP -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- 4. HikariCP -->
<!--
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:xe" />
<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>
-->
<!-- 5. MariaDB -->
<!--
<bean id="dataSource4" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="org.mariadb.jdbc.Driver"/>
<property name="url" value="jdbc:mariadb://localhost:3306/test"></property>
<property name="username" value="root"/>
<property name="password" value="test"/>
</bean>
-->
<!-- 6. MyBatis -->
<!--
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource4"/>
<property name="configLocation" value="classpath:mybatis/config.xml"/>
<property name="mapperLocations" value="classpath:mybatis/sql/*.xml"></property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource4"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
-->
6. TestUnit.java (com/website/example/unit)
package com.website.example.unit;
import static org.junit.jupiter.api.Assertions.*;
import java.sql.Connection;
import java.sql.SQLException;
import javax.inject.Inject;
import javax.sql.DataSource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
class TestUnit {
private DataSource dataSource;
private ApplicationContext ctx;
// 태스트 환경에서 Autowired 버리기(JUnit 5 to Spring Framework 4.24 일 떄)
@Test
void test() {
// 방법 1. (ApplicationContext로 Bean 불러오기)
ctx = new GenericXmlApplicationContext("applicationContext.xml");
this.dataSource = (DataSource) ctx.getBean("dataSource");
if ( this.ctx != null ) {
System.out.println("야1");
}
if ( this.dataSource != null ) {
System.out.println("야2");
}
try(Connection con = dataSource.getConnection()){
System.out.println("참");
}catch(Exception e)
{
//fail(e.getMessage());
System.out.println("거짓");
}
}
}
파일명: TestUnit.java
[첨부(Attachments)]
* 맺음글(Conclusion)
연속해서 /src/main/webapp/WEB-INF/spring/root-context.xml 등의 작업을 소개하면 이해가 되지 않을 수 있어서 핵심 위주로 간단하지만,
중요한 키 포인트를 위주로 정리하였다.
환경 셋팅 관련해서 허공에 삽질을 적게 하였으면 하는 바람이다.
[Tomcat 배포, 웹 개발]
1. [Spring Framework] 39. Beans와 Context-XML 방식으로 DB 설정 그리고 Autowired - (Web.xml), 2020-10-10