1.在spring中,面向方面的编程需要把程序逻辑分解成不同的部分称为所谓的关注点。跨一个应用程序的多个点的功能被称为横切关注点,这些横切关注点在概念上独立于应用程序的业务逻辑。有各种各样的常见的很好的方面的例子,如日志记录、审计、声明式事务、安全性和缓存等.
2.在 OOP 中,关键单元模块度是类,而在 AOP 中单元模块度是方面。依赖注入帮助你对应用程序对象相互解耦和 AOP 可以帮助你从它们所影响的对象中对横切关注点解耦。AOP 是像编程语言的触发物,如 Perl,.NET,Java 或者其他。
3.Spring AOP 模块提供拦截器来拦截一个应用程序,例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。
4.实例 添加aop依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
5.编写实体类Man
@Component //交给Spring容器管理创建对象
public class Man {
public void eat(){
System.out.println("吃东西!!!");
}
}
6.Aspect切面方法
@Aspect
@Component
@EnableAspectJAutoProxy//默认true打开,可以不用开启
public class ManAspect {
// 1.声明切面
public static final String POINTCUT1 = "execution(* com.wang.springboot.domain.Man.eat(..))";
// 2.前置通知增强 声明
@Before(POINTCUT1)
public void before(){
System.out.println("饭前先喝汤!!!");
}
// 2.后置增强 声明
@After(POINTCUT1)
public void after(){
System.out.println("饭后刷盘子!!!");
}
// 3.环绕通知 异常增强 声明
/*@Around(POINTCUT1)
public void around(ProceedingJoinPoint proceedingJoinPoint){
before();
proceedingJoinPoint.proceed();
after();
}*/
// 4.异常通知
@AfterThrowing(value = POINTCUT1,throwing = "tw")
public void exp(Throwable tw){
System.out.println("这里出现异常!!!");
}
}
7.测试
@SpringBootTest
class SpringbootAopApplicationTests {
@Autowired
private Man man;
@Test
void contextLoads() {
man.eat();
}
}
8.运行结果如下:
饭前先喝汤!!!
吃东西!!!
饭后刷盘子!!!
评论