切面相当于一个功能的某一个类,切入点是这个类的某部分和需要额外执行的其他代码块,这两者是多对多的关系,在代码块处指定执行的条件。
Aspect1.java
package com.yh.aop.schema.advice.myAspect; public class Aspect1 { public void doIt() { System.out.println("Aspect1:do"); }
}
PointCut1.java
package com.yh.myPointCut; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Component @Aspect public class PointCut1 { @Before("execution(* com.yh.aop.schema.advice.myAspect.Aspect1.*(..))") public void before() { System.out.println("PointCut1:before"); } }
applicationContext.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" xmlns:p="http://www.springframework.org/schema/p" 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-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd"> <context:component-scan base-package="com.yh"></context:component-scan> <context:component-scan base-package="com.yh.myPointCut"></context:component-scan> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <bean id="aspect1" class="com.yh.aop.schema.advice.myAspect.Aspect1"></bean> </beans>
MyTest.java
@Test public void testPointCut(){ String xmlPath="applicationContext.xml"; ApplicationContext context = new ClassPathXmlApplicationContext(xmlPath); Aspect1 aspect1 = (Aspect1) context.getBean("aspect1"); aspect1.doIt(); }