如图是我们这个实例需要弄的几个程序:
Cirle类:
package com.example.Rectangle;
import org.springframework.stereotype.Service;
@Service("circlearea")
public class Circle implements Shape {
@Override
public double area(double r,double x) throws IllegalArgumentException {
double s = x * r;
System.out.println("长方形的面积是:"+s);
return s;
}
}
切面类MyAspect :
package com.example.Rectangle;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
@EnableAspectJAutoProxy(exposeProxy=true)
@Component
@Aspect
public class MyAspect {
//public final Logger LOGGER = LogManager.getLogger(this.getClass().getName());
/*
* execution 表达式第一个*表示匹配任意的方法返回值,里有个 空格 !;
* (两个点)表示零个或多个,第一个..表示 module 包及其子包;第二个*表示所有类,
* 第三个*表示所有方法;第二个..表示方法的任意参数个数
*/
@Pointcut("execution(* com.example.Rectangle.*.*(..))")
public void pointCut(){}
@Before("pointCut()")
public void before()
{
System.out.println("开始计算...");
}
@AfterReturning("pointCut()")
public void afterReturning()
{
System.out.println("返回值...");
}
@After("pointCut()")
public void after()
{
System.out.println("结束计算...");
}
@AfterThrowing("pointCut()")
public void afterThrowing()
{
System.out.println("afterThrowing...");
}
}
接口Shape:
package com.example.Rectangle;
public interface Shape {
double area(double r,double x);
}
测试类:
package com.example.Rectangle;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@ComponentScan("com.example.Rectangle.*")
@EnableAspectJAutoProxy()
public class TestAop {
public static void main(String[] args){
ApplicationContext actx = new
ClassPathXmlApplicationContext("AOP.xml");
Shape circle = (Shape) actx.getBean("circlearea");
double d= circle.area(20,2);
}
}
最后我们不要忘记要配置序:用@Service("circlearea")注解把Circle作为一个Bean,扫描到Circle所在的包。
AOP.xml
<!--Rectangle-->
<context:component-scan base-package="com.example.Rectangle"/>
根据上面所描述你就体验AOP的快感。最后我还是想说如果做都不好,也可以指出,我会学习!很开心能帮助你!