1.配置切点
/**
* 切点
* @Component默认是类名首字母小写,也可以写成 @Component("demo123")进行自定义
* @author BarryLee
* @2018年11月14日@上午8:50:51
*/
@Component("demo123")
public class Demo {
//配置切点
@Pointcut("execution(* cn.bl.testAOP3.Demo.demo1())")
public void demo1() {
System.out.println("hello annotation aop .. ");
}
}
2.配置通知
/**
* 通知
* @Component表示要创建一个bean
* @Aspect表示该类是一个通知
* @author BarryLee
* @2018年11月14日@上午9:43:44
*/
@Component
@Aspect
public class MyAdvice {
//前置
@Before("cn.bl.testAOP3.Demo.demo1()")
public void before() {
System.out.println("前置");
}
//后置
@After("cn.bl.testAOP3.Demo.demo1()")
public void after() {
System.out.println("后置");
}
//环绕
@Around("cn.bl.testAOP3.Demo.demo1()")
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("环绕 - 前");
Object object = point.proceed();//放行,此处抛出异常
System.out.println("环绕 - 后");
return object;
}
}
3.applicationContext
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd ">
<!-- 自动扫描这个包下的@Component,为其创建bean -->
<context:component-scan base-package="cn.bl.testAOP3"></context:component-scan>
<!--
自动代理方式
proxy-target-class="true" - 使用cglib动态代理
proxy-target-class="false" - 使用jdk动态代理
默认jdk,spring是使用cglib的,需要改为true(经过测试,使用false也可以正常运行)
-->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
4.测试
/**
* 注解方式实现AOP
* @author BarryLee
* @2018年11月14日@上午8:50:51
*/
public class TestDemo {
@Test
public void test1() {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("cn/bl/testAOP3/applicationContext.xml");
String[] names = context.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
/*
demo123
myAdvice
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
org.springframework.aop.config.internalAutoProxyCreator
*/
}
@Test
public void test2() {
@SuppressWarnings("resource")
ApplicationContext context = new ClassPathXmlApplicationContext("cn/bl/testAOP3/applicationContext.xml");
Demo demo = context.getBean("demo123",Demo.class);
demo.demo1();
/*
环绕 - 前
前置
hello annotation aop ..
环绕 - 后
后置
*/
}
}