基于javaconfig的Spring的面向切面编程,术语有通知(advice)、切点(pointcut)、和连接点(joinpoint)。
通知:定义了切面是什么以及何时使用,spring有五种通知方式:
1.前置通知before:再目标方法前调用通知
2.后置通知after:在目标方法后调用通知
3.返回通知afterReturn:在目标方法返回后调用通知
4.异常通知afterThrowing:在目标方法异常后调用通知
5.环绕通知arount:在目标方法前后执行逻辑;
切点:就是在何处调用通知,spring是基于方法的面向切面,所以切点就是目标方法;
连接点:就是通知在什么时机调用;
切面:就是通知和切点的结合,即描述了是什么,在何处、何时调用;
示例:
/**
* AOP方法
* Created by 15692 on 2019/3/14.
*/
@Aspect
public class AopDemo {
@Pointcut(value = "execution(* nui.honest.spring.demo.aop.demo.BasePojo.test(..))")
public void cut() {
}
@Before("cut()")
public void before() {
System.out.println("Before Test is running");
}
@After("cut()")
public void after() {
System.out.println("After test() is running");
}
@AfterThrowing("cut()")
public void afteeException() {
System.out.println("AfterException test() is runnting");
}
@AfterReturning("cut()")
public void afterReturn() {
System.out.println("AfterReturning test() is running");
}
@Around("cut()")
public void around(ProceedingJoinPoint joinPoint) throws Exception {
try {
System.out.println("Around Before test() is running");
joinPoint.proceed();
System.out.println("Around after test() is running");
}catch (Throwable throwable) {
System.out.println("Around throw Excetption test() is running");
throw new Exception("arrasdfas");
// throwable.printStackTrace();
}
}
}
/**
* 目标方法
* Created by 15692 on 2019/3/14.
*/
@Component
public class BasePojo {
public void test() throws Exception {
System.out.println("AOP Test POJO");
throw new Exception("Exception throwed");
}
}
/**
* 配置
* Created by 15692 on 2019/3/14.
*/
@ComponentScan(value={"nui.honest.spring.demo.aop"})
@Configuration
@EnableAspectJAutoProxy
public class DemoConfig {
@Bean
public AopDemo aopDemo() {
return new AopDemo();
}
}
/**
* junit测试
* Created by 15692 on 2019/3/14.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = DemoConfig.class)
public class AOPDemoTest {
@Autowired
private BasePojo basePojo;
@Test
public void aopDemoTest() {
try {
basePojo.test();
} catch (Exception e) {
System.out.println("i am error");
}
}
}