在這個例子中,我使用aspjectj包裝標有一個自定義的註釋方法適用JPA交易:github example。
Plugins.sbt
logLevel := Level.Warn
resolvers += "Typesafe repository" at "http://repo.typesafe.com/typesafe/releases/"
addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.2.1")
// Used to weave Logger calls in Controllers and service
addSbtPlugin("com.typesafe.sbt" % "sbt-aspectj" % "0.9.4")
build.scala
import com.typesafe.sbt.SbtAspectj.AspectjKeys.inputs
import com.typesafe.sbt.SbtAspectj._
import sbt.Keys._
import sbt._
object Build extends Build {
val appName = "Interceptor"
val appVersion = "1.0-SNAPSHOT"
val main = play.Project(appName, appVersion)
.settings(aspectjSettings: _*)
.settings(inputs in Aspectj <+= compiledClasses,
products in Compile <<= products in Aspectj,
products in Runtime <<= products in Compile)
}
自定義註解
package service;
/**
* @author z.benrhouma
* @since 09/09/2014
*/
public @interface STransaction {
}
事務方面:
package aspects;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import play.db.jpa.JPA;
import play.libs.F;
/**
* @author z.benrhouma
* @since 29/03/2014
*/
@Aspect
public class TransactionAspect {
@Around("execution(* service.*.*(..)) && @annotation(service.STransaction)")
public Object logAccessRules(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
JPA.withTransaction(new F.Callback0() {
@Override
public void invoke() throws Throwable {
thisJoinPoint.proceed();
}
});
return null;
}
}
例如:
package service;
/**
* @author z.benrhouma
* @since 09/09/2014
*/
public class TransactionService {
@STransaction // --> this method will be wrapped with JPA.withTransaction
public static void doSomeProcessing(){
System.out.println("hello with transaction");
}
public static void doSomeProcessing2(){
System.out.println("hello without transaction");
}
}
@Transactional只能在操作方法中。 – 2014-09-05 11:31:34
您可以添加自定義註釋處理器幷包裝事務代碼。 – 2014-09-05 16:19:50