AOP编程手把手实例

该文展示了如何在Spring框架中利用AspectJ进行AOP编程。定义了一个Circle类实现Shape接口,用于计算面积。同时创建了MyAspect切面类,包含Before、AfterReturning、After和AfterThrowing通知,实现方法调用前后的日志记录和异常处理。通过@Pointcut定义切入点,@Service注解将Circle类作为Bean,最后在测试类中应用并验证AOP功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如图是我们这个实例需要弄的几个程序:

 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的快感。最后我还是想说如果做都不好,也可以指出,我会学习!很开心能帮助你! 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值