文章目录
Spring AOP 切点
认识Spring切点
spring AOP时基于动态代理实现的,所以只支持方法级别的连接点,所以切点支持方法级别的定义
因为Spring借鉴了AspectJ的切面技术,使用的方式和AspectJ注解切面完全一致
使用AspectJ来表达一个简单的切点
注解的方式,通过execution来匹配连接点的执行方法
@Aspect
public class AspectsTest {
//这里则是定义的 切点
@Before(value = "execution(* com.test.springdome01.AopTest.*(..))")
public void aopBeforeTest(){
}
}
切点的规则
定义一个连接点
public interface AopTest {
public String AopTestPrint();
public String AopTestPrint(String print);
}
实现类
@Component
public class AopTestImpl implements AopTest {
public String AopTestPrint() {
System.out.println("invoke AopTestPrint no arg method");
return null;
}
public String AopTestPrint(String print) {
System.out.println("invoke AopTestPrint arg method");
return null;
}
}
定义一个测试类
public class Test_AOP {
private ApplicationContext ac;
private ApplicationContext ac1;
{
ac = new AnnotationConfigApplicationContext(SpringConfig.class);
ac1 = new ClassPathXmlApplicationContext("application02.xml");
}
}
指定方法范围:execution
定义切面(切点、通知)
指定类型,参数的切点
//定义切面
@Aspect
@Component
public class AspectsTest {
//通知 //定义切点
@Before(value = "execution(String com.test.springdome01.AopTest.AopTestPrint(String))")
public void aopBeforeTest(){
System.out.println("invoke AspectsTest aopBeforeTest");
}
}
测试方法
@Test
public void test01(){
AopTestImpl bean1 = ac.getBean(AopTestImpl.class);
bean1.AopTestPrint();
System.out.println("--------------");
bean1.AopTestPrint(null);
}
注解的方式定义切点
上方标签:切点的规则
就是使用注解方式定义切点
XML方式定义切点
连接点还是使用上方标签:定义一个连接点
定义切面使用的pojo
@Component
public class AspectsTest {
public void aopBeforeTest(){
System.out.println("invoke AspectsTest aopBeforeTest");
}
}
XML配置定义切点
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!-- 扫描包 -->
<context:component-scan base-package="com.test.springdome01"/>
<!-- 开启切面代理模式 -->
<aop:aspectj-autoproxy />
<aop:config>
<!-- 定义切面 -->
<aop:aspect ref="aspectsTest">
<!-- 定义通知 --> <!-- 定义切点 -->
<aop:before method="aopBeforeTest" pointcut="execution(String com.test.springdome01.AopTest.AopTestPrint(String))"></aop:before>
</aop:aspect>
</aop:config>
</beans>
测试方法
@Test
public void test02(){
AopTestImpl bean1 = ac1.getBean(AopTestImpl.class);
bean1.AopTestPrint();
System.out.println("--------------");
bean1.AopTestPrint(null);
}