Spring AOP

文章通过SpringAOP的注解方式展示了如何实现顾客购买电冰箱的业务逻辑,包括顾客欢迎信息、购买限制(每位顾客只能购买一台特价冰箱)和欢送信息。首先,定义了销售接口及其实现,然后创建了一个通知类用于在购买方法执行前后插入操作。通过配置类启用AspectJ自动代理,确保通知类生效。最后,测试类验证了购买限制和信息提示功能。

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

Spring AOP (纯注解)

文档

某商场进行电冰箱促销活动,规定每位顾客只能购买一台特价冰箱,顾客在购买电冰箱之前输出欢迎信息,顾客如果购买多台特价冰箱,请给出错误提示,顾客成功购买电冰箱之后输出欢送信息,请使用Spring面向切面编程实现该需求的顾客欢迎信息提示。

实现思路:

1.定义出售电冰箱的接口和接口实现

2.定义前置通知

3.编写配置文件

引入依赖
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.24</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>5.3.24</version>
    </dependency>
配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan({"com.hngc"})
//启用AOP开发
@EnableAspectJAutoProxy
public class SpringConfig {
}

@EnableAspectJAutoProxy注解用于启用AOP开发,启用后,在您的应用程序上下文中定义的任何具有@AspectJ 方面(具有注释@Aspect)的类的bean 都会被Spring 自动检测到并用于配置Spring AOP。

通知类
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class Inform {
    @After("execution(* com.hngc..RefrigeratorService*.buy(..))")
    public void ha(){
        System.out.println("欢迎下次光临...");
    }
}

接口及实现
public interface RefrigeratorService {
    void buy(int number);
}
import com.hngc.service.RefrigeratorService;
import org.springframework.stereotype.Service;

@Service
public class RefrigeratorServiceImpl implements RefrigeratorService {

    @Override
    public void buy(int number) throws RuntimeException{
        if (number>1){
            System.err.println("每位顾客只能购买一台特价冰箱");
        }
    }
}
测试类
import com.hngc.config.SpringConfig;
import com.hngc.service.RefrigeratorService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(SpringConfig.class);
        RefrigeratorService refrigeratorService = applicationContext.getBean(RefrigeratorService.class);
        refrigeratorService.buy(1);

    }
}
运行结果
每位顾客只能购买一台特价冰箱
欢迎下次光临...

进程已结束,退出代码0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值