본문 바로가기

Dev & Tip/Spring

SpringBoot AOP Java 코드로 설정

기존 Spring에서 Aop방식은  XML에 선언하여 사용 했었음.

boot로 넘어오면서 AOP Pointcut으로 transcation을 method 이름으로 걸수 있을지 고민하다가 찾던 방법 중 한개를 기록함.

JPA를 쓰면서 @Transcation을 많이 사용하지만 AOP method이름 으로 설정하고 싶을때 xml방식이 아닌 방법으로 쓰기 좋음.

그래서 한 코드 작성한지 2년 된것 같은대, 개발 자료 정리겸 공유함.

@Configuration
@Aspect
@EnableTransactionManagement
@EnableAspectJAutoProxy(proxyTargetClass=true)
public class WebTransactionConfig {

    private static final int TX_METHOD_TIMEOUT = 3;
    private static final String AOP_POINTCUT_EXPRESSION = "execution(* com.sample.ubot..*Service.*(..))";

    @Autowired
    PlatformTransactionManager transactionManager;

    @Bean
    public TransactionInterceptor txAdvice(){
        // this java code cloud converting AOP and Transaction .xml file setting
        // example : <tx:advice id="txAdvice" transaction-manager="txManager">
        //		        <tx:attributes>
        //			        <tx:method name="select*" read-only="true" />

        Properties txAttributes = new Properties();

        DefaultTransactionAttribute readOnlyAttribute = new DefaultTransactionAttribute(TransactionDefinition.PROPAGATION_REQUIRED);
        readOnlyAttribute.setReadOnly(true);
        readOnlyAttribute.setTimeout(TX_METHOD_TIMEOUT);

        RuleBasedTransactionAttribute writeAttribute = new RuleBasedTransactionAttribute();
        writeAttribute.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        //List<RollbackRuleAttribute> rollbackList = Collections.singletonList(new RollbackRuleAttribute(Exception.class));
        writeAttribute.getRollbackRules().add(new RollbackRuleAttribute(Exception.class));

        //writeAttribute.setRollbackRules(rollbackList);
        writeAttribute.setTimeout(TX_METHOD_TIMEOUT);

        String readOnlyTransactionAttributesDefinition = readOnlyAttribute.toString();
        String writeTransactionAttributesDefinition = writeAttribute.toString();

        txAttributes.setProperty("select*",readOnlyTransactionAttributesDefinition);

        txAttributes.setProperty("insert*",writeTransactionAttributesDefinition);
        txAttributes.setProperty("update*",writeTransactionAttributesDefinition);
        txAttributes.setProperty("delete*",writeTransactionAttributesDefinition);

        TransactionInterceptor txAdvice = new TransactionInterceptor(transactionManager,txAttributes);

        return txAdvice;
    }

    @Bean
    public Advisor txAdviceAdvisor(TransactionInterceptor txAdvice){
        //pointcut .xml setting
        //example : <aop:pointcut id="tx" expression="execution(* com.sample.ubot..*Service.*(..))"/>

        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);

        return new DefaultPointcutAdvisor(pointcut, txAdvice);
    }

}