기존 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);
}
}
'Dev & Tip > Spring' 카테고리의 다른 글
Spring session data redis 서비스 적용 후기 (0) | 2020.12.13 |
---|---|
Spring-boot-webflux netty로 실행 안되는 증상 (0) | 2020.11.24 |