For investors
股价:
5.36 美元 %For investors
股价:
5.36 美元 %认真做教育 专心促就业
昆明达内培训机构的老师今天给大家讲注解增强方式实现前置增强和后置增强。
源码介绍:
1.UserService.java
package cn.service;
//业务处理类
public class UserService {
//方法
public void delete() {
System.out.println("delete success!");
}
}
2.AnnotationAdvice.java(注解增强)
package cn.aop;
//注解增强
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class AnnotationAdvice {
//定义前置增强
@Before("execution(* cn.service.UserService.*(..))")
public void before(JoinPoint jp) {
System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,参数:"+jp.getArgs()+",参数个数:"+jp.getArgs().length);
System.out.println("before");
}
//定义后置增强
@AfterReturning(pointcut="execution(* cn.service.UserService.*(..))",returning="returnValue")
public void afterReturning(JoinPoint jp,Object returnValue) {
System.out.println("调用"+jp.getTarget()+"的"+jp.getSignature().getName()+"方法,参数:"+jp.getArgs()+",返回值为:"+returnValue);
System.out.println("after");
}
}
注:
java.lang.Object[] getArgs():获取连接点方法运行时的入参列表
Signature getSignature():获取连接点的方法签名对象
java.lang.Object getTarget():获取连接点所在的目标对象
java.lang.Object getThis():获取代理对象本身
3.applicationContext.xml(Spring配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="#/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="#/schema/aop"
xmlns:p="#/schema/p"
xsi:schemaLocation="
#/schema/beans
#/schema/beans/spring-beans.xsd
#/schema/aop
#/schema/aop/spring-aop-4.1.xsd
">
<bean id="service" class="cn.service.UserService" />
<bean id="error" class="cn.aop.AnnotationAdvice" />
<!--针对AOP的配置-->
<aop:aspectj-autoproxy />
</beans>
4.MyTest.java
package cn.test;
//注解增强测试
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.service.UserService;
public class MyTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService biz=(UserService)ctx.getBean("service");
biz.delete();
System.out.println("success!");
}
}
学IT就到昆明达内IT培训机构!了解详情请登陆昆明达内IT培训官网(km.tedu.cn)!