1.作用对象
public class Person {
private Integer id;
private String name;
// getter setter省略
public void findPerson() {
Person person = new Person(1, "JDK");
System.out.println("findperson 被执行");
}
}
<bean id="person" class="beans.Person">
<property name="id" value="2"></property>
<property name="name" value="Python"></property>
</bean>
2.方法一:Java API
public class MyAdvice implements MethodBeforeAdvice, AfterReturningAdvice {
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println("准备执行方法: " + method.getName());
}
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println(method.getName() + " 方法执行结束");
}
}
<!-- 定义advisor -->
<bean id="myAdvice" class="aop.MyAdvice"></bean>
<!-- 配置规则, 拦截方法名为 find* -->
<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="myAdvice"></property>
<property name="pattern" value="beans.*.find.*"></property>
</bean>
<!-- 定义DefaultAdvisorAutoProxyCreator 使所有的 advisor配置自动生效 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>
3.方法二:AspectJ
@Aspect
public class MyAspectJ {
// 配置拦截类 Person
@Pointcut("execution(* beans.Person.*(..))")
public void pointCut() {
}
@Before("pointCut()")
public void doBefore() {
System.out.println("执行doBefore方法");
}
@After("pointCut()")
public void doAfter() {
System.out.println("执行doAfter方法");
}
}
<!-- 开启@AspectJ的注解 -->
<aop:aspectj-autoproxy/>
<bean class="aop.MyAspectJ"></bean>
4.方法三:XML aop标签
public class MyPointcut {
public void doBefore() {
System.out.println("执行 doBefore方法");
}
public void doAfter() {
System.out.println("执行 doAfter 方法");
}
}
<!-- 拦截处理类 -->
<bean id="myPointcut" class="aop.MyPointcut"></bean>
<aop:config>
<!-- 拦截规则配置 -->
<aop:pointcut id="pointcutConfig" expression="execution(* beans.Person.*(..))"></aop:pointcut>
<!-- 拦截方法配置 -->
<aop:aspect ref="myPointcut">
<aop:before method="doBefore" pointcut-ref="pointcutConfig"></aop:before>
<aop:after method="doAfter" pointcut-ref="pointcutConfig"></aop:after>
</aop:aspect>
</aop:config>
5.测试
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Person person = context.getBean("person", Person.class);
person.findPerson();
本文详细介绍了如何在Spring框架中使用AOP(面向切面编程)来增强代码的功能,包括通过Java API、AspectJ和XML aop标签三种方式实现方法前、后通知和点切面的配置。
3452

被折叠的 条评论
为什么被折叠?



