AOP Maven包:
org.springframework spring-aop org.springframework spring-aspects
方式一:Spring AOP 1.x 配置
包的结构:
- 先定义一个Service的接口
public interface TestSerivce {
public void logIn();
public boolean test();
public void logOut();
}
- 然后实现这个接口
public class TestServiceImpl implements TestSerivce{
@Override
public void logIn() {
System.out.println("LogIn success");
}
@Override
public boolean test() {
try{
System.out.println("test success");
return true;
}catch (Exception e){
e.getMessage();
return false;
}
}
@Override
public void logOut() {
System.out.println("Logout success");
}
}
- 定义增强类:
a. 前置通知:
public class BeforeAdvice implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("This is Before Advice");
}
}
b. 后置通知
public class AfterAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("This is a after advice");
}
}
c. 环绕通知
```java
public class AroundAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
System.out.println("环绕执行开始");
//执行目标
Object proceed = methodInvocation.proceed();
System.out.println("环绕执行结束");
return proceed;
}
}
d. 异常通知:
public class ExceptionAdvice implements ThrowsAdvice {
// 可以利用重载抓取不同类型的Exception
public void afterThrowing(NullPointerException nullPointerException){
System.out.println(nullPointerException.getMessage());
System.out.println("Get a Null exception");
}
public void afterThrowing(Exception e){
System.out.println(e.getMessage());
}
}
- xml配置:
logIn
test
test
logIn test logOut
aop01.service.TestSerivce
beforeMethod afterMethod aroundMethod excMethod
- 运行:
public class TestAOP {
public static void main(String[] args) {
ApplicationContext app=new ClassPathXmlApplicationContext("aop01/aopConfig.xml");
TestSerivce testService =(TestSerivce) app.getBean("testService");
testService.logIn();
testService.test();
testService.logOut();
}
}
- 运行结果:



