Spring注解(完结)

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>
发布了38 篇原创文章 · 获赞 38 · 访问量 2736

猜你喜欢

转载自blog.csdn.net/l13kddd/article/details/105237043
今日推荐