본문 바로가기

IT, 인터넷/JAVA, 스프링부트

스프링부트 트랜잭션 관리하기(aop 방식)

반응형

트랜잭션은 꼭 개발시에 관리를 해주어야 하는데요.

트랜잭션을 한방에 처리 할수있는 aop방식이 있습니다.

aop 방식은 한방에 모든 파일을 관리를 하도록 하는 방식인데 많이 사용되는 방식입니다.

먼저 config파일을 만들어 주어야 합니다. TransactionAspect.java라는 파일을 만들어 보겠습니다.

TransactionAspect.java

import java.util.Collections;

import java.util.HashMap;

 

import org.springframework.aop.Advisor;

import org.springframework.aop.aspectj.AspectJExpressionPointcut;

import org.springframework.aop.support.DefaultPointcutAdvisor;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.transaction.PlatformTransactionManager;

import org.springframework.transaction.TransactionDefinition;

import org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource;

import org.springframework.transaction.interceptor.RollbackRuleAttribute;

import org.springframework.transaction.interceptor.RuleBasedTransactionAttribute;

import org.springframework.transaction.interceptor.TransactionAttribute;

import org.springframework.transaction.interceptor.TransactionInterceptor;

 

@Configuration

public class TransactionAspect {

 

    @Autowired

    PlatformTransactionManager transactionManager;

 

    @Bean

    public TransactionInterceptor transactionAdvice() {

        NameMatchTransactionAttributeSource txAttributeSource = new NameMatchTransactionAttributeSource();

        RuleBasedTransactionAttribute txAttribute = new RuleBasedTransactionAttribute();

 

        txAttribute.setRollbackRules(Collections.singletonList(new RollbackRuleAttribute(Exception.class)));

        txAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);

 

        HashMap<String, TransactionAttribute> txMethods = new HashMap<String, TransactionAttribute>();

        txMethods.put("*", txAttribute);

        txAttributeSource.setNameMap(txMethods);

 

        return new TransactionInterceptor(transactionManager, txAttributeSource);

    }

 

    @Bean

    public Advisor transactionAdviceAdvisor() {

        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();

        pointcut.setExpression("execution(* 전체패키지명..service.impl.*Impl.*(..))");

        return new DefaultPointcutAdvisor(pointcut, transactionAdvice());

    }

}

 

위에거 대로 작성을 하면 service.impl 패키지 안에 Impl로 끝나는 자바의 모든 파일의 메소드에 트랜잭션을 거는 것입니다. 이렇게 한방에 트랜잭션을 걸수 있는 방법이 있습니다. 이게 aop 방식 인거죠

execution(* 전체패키지명..service.impl.*Impl.*(..)) 이렇게하면 전체패키지 안에 Impl로 끝나는 모든메소드에 트랜잭션을

건다는 겁니다.

반응형