0
点赞
收藏
分享

微信扫一扫

Spring AOP-通知-为目标方法织入多个切面

yundejia 2022-06-24 阅读 63

AOP-通知-为目标方法织入多个切面

开发中可能会遇到为目标方法织入多个切面,比如前置。后置通知都需要

接口

package com.hk.spring.aop06;

public interface SomeService {

public void doFirst();
public void doSecond();
}

接口实现

package com.hk.spring.aop06;

public class SomeServiceImpl implements SomeService {

@Override
public void doFirst() {

System.out.println("主业务doFirst");
}

@Override
public void doSecond() {

System.out.println("主业务doSecond");
}

}

前置通知

kpackage com.hk.spring.aop06;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
* 前置通知
* @author 浪丶荡
*
*/
public class MyMethodBeforeAdvice implements MethodBeforeAdvice {

//在目标方法执行之前执行
@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("前置通知执行");
}

}

后置通知

package com.hk.spring.aop06;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;

/**
* 后置通知
* @author 浪丶荡
*
*/
public class MyAfterReturningAdvice implements AfterReturningAdvice {

//在目标方法执行之后执行
@Override
public void afterReturning(Object returnValue, Method method,
Object[] args, Object target) throws Throwable {
System.out.println("后置通知执行");
}


}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean name = "someService" class="com.hk.spring.aop06.SomeServiceImpl"></bean>
<!-- 注册前置通知 -->
<bean name = "myMethodBeforeAdvice" class="com.hk.spring.aop06.MyMethodBeforeAdvice"></bean>
<!-- 注册后置通知 -->
<bean name = "myAfterReturningAdvice" class="com.hk.spring.aop06.MyAfterReturningAdvice"></bean>
<!-- 生成代理对象 -->
<bean name = "serviceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<!-- 配置代理对象的目标对象属性 (类加载器)-->
<property name="target" ref="someService"/>
<!-- 或者这样配置
<property name="targetName" value="someService"/>
-->
<!-- 配置多个切面 (方法)-->
<property name="interceptorNames" value="myMethodBeforeAdvice,myAfterReturningAdvice"/>
<!-- 接口通过private boolean autodetectInterfaces = true可以被找到 -->
</bean>

</beans>

测试

package com.hk.spring.aop06;


import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.hk.spring.aop06.SomeService;
public class Mytest {

@Test
public void test1(){
String resoure = "com/hk/spring/aop06/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resoure);
SomeService someService = (SomeService) ac.getBean("serviceProxy");
someService.doFirst();
someService.doSecond();
}
}

结果

前置通知执行
主业务doFirst
后置通知执行
前置通知执行
主业务doSecond
后置通知执行


举报

相关推荐

0 条评论