AOP註解
需要導入依賴:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
該依賴是用來支持切入點表達式
例:execution(* com.muzi.service.impl..(…))
需要提前在xml中配置Spring對AOP註解的支持:
<aop:aspect-autoproxy></aop:aspect-autoproxy>
@Aspect
@Pointcut
@Before
@AfterThrowing
@AfterReturning
@After
@Around
@EnableAspectJAutoProxy(該註解可以省略在xml中配置Spring對AOP註解的支持)
表示當前類是一個切面類
@Aspect
@EnableAspectJAutoProxy
public class Logger{
@Pointcut("execution(* com.muzi.service.impl.*.*(..))")
private void pt1(){}
@Before(“pt1()”)
public void beforePrintLog(){
System.out.println("前置通知方法執行");
}
@AfterReturning(“pt1()”)
public void afterReturningPrintLog(){
System.out.println("後置通知方法執行");
}
@AfterThrowing(“pt1()”)
public void afterThrowingPrintLog(){
System.out.println("異常通知方法執行");
}
@After(“pt1()”)
public void afterPrintLog(){
System.out.println("最終通知方法執行");
}
@Around("pt1()")
public Object aroundPrintLog(ProceedingJoinPoint pjp){
Object rtValue=null;
try{
//得到方法執行所需要的參數
Object[] args=pjp.getArgs();
System.out.println("Logger類中的aroundPointLog方法開始記錄日誌了。。。前置");
//明確調用業務層方法(切入點方法)
rtValue=pjp.proceed(args);
System.out.println("Logger類中的aroundPointLog方法開始記錄日誌了。。。後置");
return rtValue;
}catch(Throwable t){
System.out.println("Logger類中的aroundPointLog方法開始記錄日誌了。。。異常");
}finally{
System.out.println("Logger類中的aroundPointLog方法開始記錄日誌了。。。最終");
}
}
}
@Transactional
屬性:
isolation:用於指定事務的隔離級別。
no-rollback-for:用於指定一個異常,當產生該異常時,事務不回滾,產生其他異常時事務回滾,沒有默認值,表示任何事務都回滾。
propagation:用於指定事務的傳播行爲,默認值是REQUIRED,表示一定會有事務,增刪改的選擇。查詢方法可以用SUPPORTS。
read-only:用於指定事務是否只讀,只有查詢方法才能設置爲true,默認值是false,表示讀寫。
rollback-for:用於指定一個異常,當產生該異常時,事務回滾,產生其他事務時,事務不回滾,沒有默認值,表示任何事務都回滾。
timeout:用於指定事務的超時時間,默認值是-1,表示永不超時,如果指定了數值,以秒爲單位。
在需要事務支持的地方使用@Transactional註解
@Transactional
public class AccountServiceImp implements IAccountService{
}
@EnableTransactionManagement
開啓Spring事務註解的支持。
@EnableTransactionManagement
public class SpringConfiguation{
}
相當於
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>