Spring aop学习笔记
项目目录结构
pojo->C
package com.ann.pojo;
public interface C {
void testA();
}
pojo->TestA
package com.ann.pojo;
public class TestA implements C {
@Override
public void testA() {
System.out.println("我是AAAAA对象的testA方法");
}
}
pojo->TestB
package com.ann.pojo;
public class TestB implements C {
@Override
public void testA() {
// 扩展前
System.out.println("扩展前");
TestA a = new TestA();
a.testA();
// 扩展后
System.out.println("扩展后");
}
}
advice->AfterTestA
package com.ann.advice;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterTestA implements AfterReturningAdvice {
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("AfterReturningAdvice:扩展后");
}
}
advice->BeforeTestA
package com.ann.advice;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class BeforeTestA implements MethodBeforeAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("MethodBeforeAdvice:扩展前");
}
}
test->TestSpringAOP
package com.ann.test;
import com.ann.pojo.C;
import com.ann.pojo.TestA;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringAOP {
public static void main(String[] args) {
C c = new TestA();
c.testA();
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
C testA = (C)ac.getBean("TestA");
testA.testA();
}
}
test->TestSpringAOP2
package com.ann.test;
import com.ann.pojo.C;
import javafx.application.Application;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpringAOP2 {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationcontext.xml");
C c = (C) ac.getBean("TestA");
c.testA();
}
}
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"
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-4.3.xsd">
<!-- 配置业务bean-->
<bean id="TestA" class="com.ann.pojo.TestA"></bean>
<bean id="before" class="com.ann.advice.BeforeTestA"></bean>
<bean id="after" class="com.ann.advice.AfterTestA"></bean>
<!-- 配置Aop-->
<aop:config>
<!-- 配置扩展对象-->
<aop:pointcut id="pc" expression="execution(* com.ann.pojo.TestA.testA())"/>
<aop:advisor advice-ref="before" pointcut-ref="pc"></aop:advisor>
<aop:advisor advice-ref="after" pointcut-ref="pc"></aop:advisor>
</aop:config>
</beans>