什么是spring aop,请详细的告诉我并给我一个demo(注解版和配置文件版),面试需要从哪方面下手,举个例子给我。
时间: 2024-03-20 20:43:19 浏览: 17
Spring AOP是Spring框架中的一个模块,它是基于AOP(面向切面编程)的思想,提供了在程序运行期间动态地将代码织入到应用程序中的能力,从而实现了对业务逻辑的解耦。
Spring AOP的核心概念是切面(Aspect)、连接点(Join Point)、切点(Pointcut)和通知(Advice)。其中,切面是横切关注点的模块化,连接点是程序执行过程中的一个特定点,切点则定义了连接点的集合,通知则是在连接点上执行的操作。
下面给出注解版和配置文件版的demo代码:
1. 注解版
切面类:
```java
@Aspect
@Component
public class LogAspect {
@Pointcut("execution(* com.example.demo.service.*.*(..))")
public void log() {}
@Before("log()")
public void before(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Before " + methodName);
}
@AfterReturning("log()")
public void afterReturning(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("AfterReturning " + methodName);
}
@AfterThrowing(pointcut = "log()", throwing = "ex")
public void afterThrowing(JoinPoint joinPoint, Exception ex) {
String methodName = joinPoint.getSignature().getName();
System.out.println("AfterThrowing " + methodName + " " + ex.getMessage());
}
@After("log()")
public void after(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("After " + methodName);
}
}
```
服务类:
```java
@Service
public class UserService {
public void addUser(String name) {
System.out.println("addUser " + name);
}
public void deleteUser(String name) throws Exception {
throw new Exception("deleteUser error");
}
}
```
2. 配置文件版
配置文件:
```xml
<aop:config>
<aop:aspect ref="logAspect">
<aop:pointcut id="log"
expression="execution(* com.example.demo.service.*.*(..))" />
<aop:before pointcut-ref="log" method="before" />
<aop:after-returning pointcut-ref="log" method="afterReturning" />
<aop:after-throwing pointcut-ref="log" method="afterThrowing"
throwing="ex" />
<aop:after pointcut-ref="log" method="after" />
</aop:aspect>
</aop:config>
<bean id="logAspect" class="com.example.demo.aspect.LogAspect" />
<bean id="userService" class="com.example.demo.service.UserService" />
```
服务类:
```java
public class UserService {
public void addUser(String name) {
System.out.println("addUser " + name);
}
public void deleteUser(String name) throws Exception {
throw new Exception("deleteUser error");
}
}
```
在面试中,你可以从以下几个方面入手:
1. AOP的基本概念和作用
2. Spring AOP的实现方式
3. 切面、连接点、切点和通知的含义和使用方法
4. AOP的应用场景和优缺点
举例来说,可以问面试者如何使用AOP实现日志记录、权限控制、事务管理等功能,同时也可以让面试者分析AOP的缺点和使用不当可能带来的问题。