전에 앞서서 진행한 pom.xml 을 변경한다.
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
위 라이브러리는 기본적으로 설정 된 것이다.
따라서
다음과 같이 변경한다. 트랜잭션 처리를 위한 라이브러리도 함께 추가한다.
<!-- 트랜잭션 처리 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!--AOP AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- AOP https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</version>
</dependency>
현재 까지 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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.macaronics</groupId>
<artifactId>web</artifactId>
<name>test02</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.3.0.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.7.21</org.slf4j-version>
</properties>
<!-- 오라클 연결 -->
<repositories>
<repository>
<id>codelds</id>
<url>https://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<dependencies>
<!-- 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>
<!-- 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>3.1.0</version>
</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>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<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>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.bgee.log4jdbc-log4j2/log4jdbc-log4j2-jdbc4 -->
<dependency>
<groupId>org.bgee.log4jdbc-log4j2</groupId>
<artifactId>log4jdbc-log4j2-jdbc4</artifactId>
<version>1.16</version>
</dependency>
<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.7</version>
<scope>test</scope>
</dependency>
<!-- 오라클 연결 드라이브 -->
<!-- https://mvnrepository.com/artifact/com.github.noraui/ojdbc7 -->
<dependency>
<groupId>com.github.noraui</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
<!-- 트랜잭션 처리 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!--AOP AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- AOP https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.11</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.6</source>
<target>1.6</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
servlet-context.xml
다음 그림과 같이 체크를 한다.

메시지 전달시 10 포이트 추가 , 메시지 확인시 5포인트 추가하는 내용이다.
위 그림과 같은 파일을 만들어서 테스트를 진행하면 된다.
sql 변경
-- tbl_member 포인트 컬럼 추가 alter table tbl_member add COLUMN ( upoint int not null default 0); alter table tbl_message add CONSTRAINT fk_usertarget foreign key (targetid) REFERENCES tbl_member (userid); alter table tbl_message add constraint fk_usersender foreign key (sender) REFERENCES tbl_member(userid);
MessageVO
package test.domain;
import java.util.Date;
public class MessageVO {
private Integer mid;
private String targetid;
private String sender;
private String message;
private Date opendate;
private Date sneddate;
상세 내용은 깃 허브 파일을 보고, 나머지는 생략 하겠다.
중요한 것은 AOP 에서 다음 과 같은 설정 내용이다.
SampleAdvice
package test.aop;
import java.util.Arrays;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class SampleAdvice {
private static final Logger logger =LoggerFactory.getLogger(SampleAdvice.class);
@Before("execution( * test.service.MessageService*.*(..))")
public void startLog() throws Throwable{
logger.info("----------------");
logger.info("-----------------");
}
@Around("execution( * test.service.MessageService*.*(..))"
+ " or execution( * test.persistence.*.*(..))")
public Object timeLog(ProceedingJoinPoint pjp) throws Throwable{
long startTime =System.currentTimeMillis();
logger.info(Arrays.toString(pjp.getArgs()));
Object result=pjp.proceed();
logger.info("----------------");
logger.info("-----------------");
long endTime=System.currentTimeMillis();
logger.info(pjp.getSignature().getName()+" : " + (endTime- startTime));
logger.info("===============================================");
return result;
}
}
ProceedingJoinPoint 는 Around 에서 만 가능하다는 것과 logger.info 에서 로그가 안찍힌다는 것이다.
log4j.xml 을 변경 하라. logback.xml 아니다. log4j.xml 을 변경 하면 된다.
<!-- Root Logger --> <root> <priority value="info" /> <appender-ref ref="console" /> </root>
REST 테스트
구글 웹 스토에서 REST 검색후 설치한다.
사용방법은 다음 이미지 와 같다.
MessageController
package test.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import test.domain.MessageVO;
import test.service.MessageService;
@RestController
@RequestMapping("/message")
public class MessageController {
@Autowired
private MessageService service;
@RequestMapping(value="/", method=RequestMethod.POST)
public ResponseEntity<String> addMessage(@RequestBody MessageVO vo){
ResponseEntity<String> entity=null;
try{
service.create(vo);
entity =new ResponseEntity<String>("SUCCESS", HttpStatus.OK);
}catch(Exception e){
e.printStackTrace();
entity=new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
return entity;
}
}
트랜잭션 설정
트랜잭션 설정 후 테스트를 통해 제대로 동작하는지 확인만 하면 된다.
1. @Transactional 애노테이션
스프링에서 트랜잭션을 처리하기 위해서 제공되는 @Transactional 애노테이션을 이용하면 간단히 트랜잭션 설정을 완료할 수 있다.
이때 지정할 수 있는 속성들은 다음과 같다.
@Tansactional 애노테이션은 몇 가지 중요한 속성을 가지고 있으나. 경우에 따라서는 속성들을 조정해서 사용해야 한다.
- 전파(Propagation) 속성 :
- PROPAGATION_MADATORY : 작업은 반드시 특정한 트랜잭션이 존재한 상태에서만 가능
- PROPAGATION_NESTED : 기존에 트랜잭션이 있는 경우, 포함되어서 실행
- PROPAGATION_NEVER : 트랜잭션 상황에 실행되면 예외 발생
- PROPAGATION_NOT_SUPPORTED : 트랜잭션이 있는 경우에는 트랜잭션이 끝날 때까지 보류된 후 실행
- PROPAGATION_REQUIRED : 트랜잭션이 있으며 그 상황에서 실행, 없으면 새로은 트랜잭션 실행(기본 설정)
- PROPAGATION_REQUIRED_NEW : 대상은 자신만의 고유한 트랜잭션으로 실행
- PROPAGATION_SUPPORTS : 트랜잭션을 필요로 하지 않으나, 트랜잭션 상황에 있다면 포함되어서 실행
- 격리(Isolation) 레벨
- DEFAULT : DB 설정, 기본 경리 수준( 기본 설정)
- SERIALIZABLE: 가장 높은 격리, 성능 저하의 우려가 있음
- READ_UNCOMMITED : 커밋되지 않은 데이터에 대한 읽기를 허용
- READ_COMMITED : 커밋된 데이터에 대해 읽기 허용
- REPEATEABLE_READ : 동일 필드에 대해 다중 접근 시 모두 동일한 결과를 보장
- Read-only 속성
- true 인 경우 insert, update, delete 실행시 예외 발생, 기본 설정은 false
- Rollback-for-예외
- 특정 예외가 발생 시 강제로 Rollback
- No-rollback-for-예외
- 특정 예외의 발생시 Rollback 처리되지 않음
2. root-context.xml 에 다음과 같이 처리를 한다.
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <tx:annotation-driven/>
3. 두개의 작업이 필요한 곳에 트랜잭션 적용 한다.
MessageServiceImpl
package test.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.domain.MessageVO;
import test.persistence.MessageDAO;
import test.persistence.PointDAO;
@Service
public class MessageServiceImpl implements MessageService{
@Autowired
private MessageDAO messageDAO;
@Autowired
private PointDAO pointDAO;
@Transactional
@Override
public void create(MessageVO vo) throws Exception {
//메시지 보낸 사람 10 점 추가
messageDAO.create(vo);
pointDAO.updatePoint(vo.getSender(), 10);
}
@Override
public MessageVO readMessage(String userid, Integer mid) throws Exception {
//메시지를 읽으면 읽은시간을 업데이트
messageDAO.updateState(mid);
//포이트 5점 증가
pointDAO.updatePoint(userid, 5);
return messageDAO.readMessage(mid);
}
}
4. 트랜젝션이 적용되었는지 아이콘으로 확인한다.
트랜잭션만 적용된 모습 aop around 모습만 보인다.

트랜젝션과 aop 가 적용된 모습
두가지 이상의 Advice 가 적용된 모습의 아이콘을 볼 수 있다.

5. 트랜젝션이 적용되었는지 SQL 문 오류를 내어 본다.
<update id="updatePoint">
update TBL_MEMBER set upoint =upoint + #{point}
where uuuuserid=#{userid}
</update>

6. 트랜젝션이 적용되었는지 로그로 확인해 본다.
트랜잭션이 적용되면 한나의 Connection 만 열리고 처리되는 것을 볼 수 있다.
숫자 1 만 찍힌다.
INFO : jdbc.connection - 1. Connection opened
INFO : jdbc.audit - 1. Connection.new Connection returned
INFO : jdbc.audit - 1. Connection.getAutoCommit() returned true
INFO : jdbc.audit - 1. Connection.setAutoCommit(false) returned
INFO : test.aop.SampleAdvice - [MessageVO [mid=null, targetid=user01, sender=user02, message=Good Luck!, opendate=null, sneddate=null]]
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - [MessageVO [mid=null, targetid=user01, sender=user02, message=Good Luck!, opendate=null, sneddate=null]]
INFO : jdbc.audit - 1. Connection.getAutoCommit() returned false
INFO : jdbc.audit - 1. PreparedStatement.new PreparedStatement returned
INFO : jdbc.audit - 1. Connection.prepareStatement(insert into tbl_message (targetid, sender, message)
values (? , ?, ?)) returned net.sf.log4jdbc.sql.jdbcapi.PreparedStatementSpy@2eb62a89
INFO : jdbc.audit - 1. PreparedStatement.setString(1, "user01") returned
INFO : jdbc.audit - 1. PreparedStatement.setString(2, "user02") returned
INFO : jdbc.audit - 1. PreparedStatement.setString(3, "Good Luck!") returned
INFO : jdbc.sqlonly - insert into tbl_message (targetid, sender, message) values ('user01' , 'user02', 'Good Luck!')
INFO : jdbc.sqltiming - insert into tbl_message (targetid, sender, message) values ('user01' , 'user02', 'Good Luck!')
{executed in 15 msec}
INFO : jdbc.audit - 1. PreparedStatement.execute() returned false
INFO : jdbc.audit - 1. PreparedStatement.getUpdateCount() returned 1
INFO : jdbc.audit - 1. PreparedStatement.close() returned
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - create : 113
INFO : test.aop.SampleAdvice - ===============================================
INFO : test.aop.SampleAdvice - [user02, 10]
INFO : jdbc.audit - 1. PreparedStatement.new PreparedStatement returned
INFO : jdbc.audit - 1. Connection.prepareStatement(update TBL_MEMBER set upoint =upoint + ?
where userid=?) returned net.sf.log4jdbc.sql.jdbcapi.PreparedStatementSpy@280d60f2
INFO : jdbc.audit - 1. PreparedStatement.setInt(1, 10) returned
INFO : jdbc.audit - 1. PreparedStatement.setString(2, "user02") returned
INFO : jdbc.sqlonly - update TBL_MEMBER set upoint =upoint + 10 where userid='user02'
INFO : jdbc.sqltiming - update TBL_MEMBER set upoint =upoint + 10 where userid='user02'
{executed in 5 msec}
INFO : jdbc.audit - 1. PreparedStatement.execute() returned false
INFO : jdbc.audit - 1. PreparedStatement.getUpdateCount() returned 1
INFO : jdbc.audit - 1. PreparedStatement.close() returned
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - updatePoint : 6
INFO : test.aop.SampleAdvice - ===============================================
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - create : 119
INFO : test.aop.SampleAdvice - ===============================================
INFO : jdbc.audit - 1. Connection.commit() returned
INFO : jdbc.audit - 1. Connection.setAutoCommit(true) returned
INFO : jdbc.audit - 1. Connection.isReadOnly() returned false
INFO : jdbc.connection - 1. Connection closed
INFO : jdbc.audit - 1. Connection.close() returned
트랜잭션을 적용하지 않은 경우
INFO : test.aop.SampleAdvice - [MessageVO [mid=null, targetid=user01, sender=user02, message=Good Luck!, opendate=null, sneddate=null]]
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - [MessageVO [mid=null, targetid=user01, sender=user02, message=Good Luck!, opendate=null, sneddate=null]]
INFO : jdbc.connection - 3. Connection opened
INFO : jdbc.audit - 3. Connection.new Connection returned
INFO : jdbc.audit - 3. Connection.getAutoCommit() returned true
INFO : jdbc.audit - 3. PreparedStatement.new PreparedStatement returned
INFO : jdbc.audit - 3. Connection.prepareStatement(insert into tbl_message (targetid, sender, message)
values (? , ?, ?)) returned net.sf.log4jdbc.sql.jdbcapi.PreparedStatementSpy@56b62a6d
INFO : jdbc.audit - 3. PreparedStatement.setString(1, "user01") returned
INFO : jdbc.audit - 3. PreparedStatement.setString(2, "user02") returned
INFO : jdbc.audit - 3. PreparedStatement.setString(3, "Good Luck!") returned
INFO : jdbc.sqlonly - insert into tbl_message (targetid, sender, message) values ('user01' , 'user02', 'Good Luck!')
INFO : jdbc.sqltiming - insert into tbl_message (targetid, sender, message) values ('user01' , 'user02', 'Good Luck!')
{executed in 36 msec}
INFO : jdbc.audit - 3. PreparedStatement.execute() returned false
INFO : jdbc.audit - 3. PreparedStatement.getUpdateCount() returned 1
INFO : jdbc.audit - 3. PreparedStatement.close() returned
INFO : jdbc.connection - 3. Connection closed
INFO : jdbc.audit - 3. Connection.close() returned
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - create : 46
INFO : test.aop.SampleAdvice - ===============================================
INFO : test.aop.SampleAdvice - [user02, 10]
INFO : jdbc.connection - 4. Connection opened
INFO : jdbc.audit - 4. Connection.new Connection returned
INFO : jdbc.audit - 4. Connection.getAutoCommit() returned true
INFO : jdbc.audit - 4. PreparedStatement.new PreparedStatement returned
INFO : jdbc.audit - 4. Connection.prepareStatement(update TBL_MEMBER set upoint =upoint + ?
where userid=?) returned net.sf.log4jdbc.sql.jdbcapi.PreparedStatementSpy@739b5190
INFO : jdbc.audit - 4. PreparedStatement.setInt(1, 10) returned
INFO : jdbc.audit - 4. PreparedStatement.setString(2, "user02") returned
INFO : jdbc.sqlonly - update TBL_MEMBER set upoint =upoint + 10 where userid='user02'
INFO : jdbc.sqltiming - update TBL_MEMBER set upoint =upoint + 10 where userid='user02'
{executed in 70 msec}
INFO : jdbc.audit - 4. PreparedStatement.execute() returned false
INFO : jdbc.audit - 4. PreparedStatement.getUpdateCount() returned 1
INFO : jdbc.audit - 4. PreparedStatement.close() returned
INFO : jdbc.connection - 4. Connection closed
INFO : jdbc.audit - 4. Connection.close() returned
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - updatePoint : 80
INFO : test.aop.SampleAdvice - ===============================================
INFO : test.aop.SampleAdvice - ----------------
INFO : test.aop.SampleAdvice - -----------------
INFO : test.aop.SampleAdvice - create : 126
INFO : test.aop.SampleAdvice - ===============================================
제작 : macaronics.net - Developer Jun Ho Choi
소스 : https://github.com/braverokmc79/spring_simple_blog























댓글 ( 5)
댓글 남기기