本文主要记录在项目中使用spring aop 支持的 aspectj切面,用于学习记录。
先不多说,上代码。
1,增加spring配置 :
<aop:aspectj-autoproxy/>
配置之后,spring可以发现@Aspect注解的切面
2,定义一个切面类:
@Component
@Aspect
public class LockAspectJ implements Ordered {
//公共切入点,通过注解形式配置
@Pointcut("@annotation(xxx.xxx.xxx.xxxx.xx.AspectAnnotation)") //通过某注解配置节点,配置切点的方式有很多中,会在之后的博客中统一记录
public void methodPointcut() {
}
@Before("methodPointcut()")
public void before(){
System.out.println("方法执行前..........");
}
@AfterReturning("methodPointcut()")
public void afterReturning(){
System.out.println("方法执行完执行........");
}
@AfterThrowing("methodPointcut()")
public void throwss(){
System.out.println("方法异常时执行..........");
}
@After("methodPointcut()")
public void after(){
System.out.println("方法最后执行.......");
}
@Around("methodPointcut()") //环绕通知
public Object doAroundMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("方法环绕开始.........");
try {
return pjp.proceed();
} catch (Exception e) {
throw e;
} finally {
.........
}
System.out.println("方法环绕结束..........");
}
@Override
public int getOrder() {
return 0;
}
}
3,切面注解类
@Retention(RetentionPolicy.RUNTIME)
@Target({ java.lang.annotation.ElementType.METHOD })
public @interface AspectAnnotation {
//可以根据需要增加属性
}
4,需要使用切面的业务类
@Service
public class XxxxxServiceImpl {
@AspectAnnotation
public String xxxxMethod(String xxx, String xxxxx, String xx){
System.out.println("业务处理方法.........");
return "yyyyyy";
}
}
5,自我总结,可能有不对的地方,还望看到博客的java大牛给予评论
spring通过ioc注入bean的时候,发现有需要切面(代理)的方法,在注入bean的时候,spring会生成对应类的代理bean,之后通过spring获取的bean就是这个代理类的bean。