实现一
首先我们先写两个切面类:执行时间执行顺序由@Order注解决定,参数越小,顺序越先
@Aspect
@Component
@Order(0)
public class MethodAspect {
@Before("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
public void before(JoinPoint jp) {
Signature signature = jp.getSignature();
String name = signature.getName();
System.out.println("The "+ name +" method begins");
}
}
@Aspect
@Component
@Order(1)
public class ArgAspect {
@Before("execution(public int live.sunhao.calculator.service.CalculatorService.*(..))")
public void before(JoinPoint jp) {
Object [] args = jp.getArgs();
System.out.println("The"+ jp.getSignature().getName() +"method arg:["+args[0]+","+args[1]+"]");
}
}
然后配置xml文件,这里是采用自动代理的方式实现aop
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="live.sunhao"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
实现二
我们还可以手动实现aop
首先,我们把两个切面类中的所有注解去掉即可
接着,配置xml文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
<context:component-scan base-package="live.sunhao"></context:component-scan>
<bean id="argAspect" class="live.sunhao.aspect.ArgAspect"></bean>
<bean id="methodAspect" class="live.sunhao.aspect.MethodAspect"></bean>
<aop:config>
<aop:pointcut expression="execution(public int live.sunhao.calculator.service.CalculatorService.*(..))" id="pointcut"/>
<aop:aspect ref="methodAspect" order="1">
<aop:before method="before" pointcut-ref="pointcut"/>
</aop:aspect>
<aop:aspect ref="argAspect" order="2">
<aop:before method="before" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
最后我们写个测试类 测试功能即可