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