aop切面,获取参数
添加pom
1 <dependency> 2 <groupId>org.aspectj</groupId> 3 <artifactId>aspectjweaver</artifactId> 4 <version>1.8.13</version> 5 </dependency>
配置MyAspect
1 public class MyAspect implements MethodInterceptor { 2 @Override 3 public Object invoke(MethodInvocation invocation) throws Throwable { 4 return null; 5 } 6 7 public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 8 Signature signature = proceedingJoinPoint.getSignature(); 9 10 //获取方法名 11 System.out.println(signature.getName()); 12 //获取类名 13 System.out.println(signature.getDeclaringTypeName()); 14 Object[] objs = proceedingJoinPoint.getArgs(); 15 //循环输出参数 16 for (Object obj : objs) { 17 System.out.println(obj.toString()); 18 } 19 //方法执行前逻辑处理 20 System.out.println("开始"); 21 Object obj = proceedingJoinPoint.proceed(); 22 //输出执行结果 23 System.out.println(obj.toString()); 24 25 //方法执行后逻辑处理 26 System.out.println("结束"); 27 return obj; 28 } 29 }
配置Service
1 public interface UserService { 2 UserBean Say(UserBean str); 3 }
1 @Service 2 public class UsereServiceImpl implements UserService { 3 4 @Override 5 public UserBean Say(UserBean str) { 6 System.out.println("User被创建。。。。。" + str.toString()); 7 str.setName("testtest"); 8 return str; 9 } 10 }
- 配置spring.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns="http://www.springframework.org/schema/beans" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans.xsd 7 http://www.springframework.org/schema/aop 8 http://www.springframework.org/schema/aop/spring-aop.xsd"> 9 <bean name="myUserService" class="com.muyi.service.impl.UsereServiceImpl"/> 10 <bean name="MyAspect" class="com.muyi.MyAspect"/> 11 <aop:config proxy-target-class="true"> 12 <aop:aspect ref="MyAspect"> 13 <aop:pointcut id="myPointcut" expression="execution(* com.muyi.service.*.*(..))"></aop:pointcut> 14 <aop:around method="myAround" pointcut-ref="myPointcut"/> 15 </aop:aspect> 16 </aop:config> 17 </beans>
Test
1 @Test 2 public void bean2() { 3 ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml"); 4 UserService userService = (UserService) context.getBean("myUserService"); 5 UserBean userBean = new UserBean(); 6 userBean.setAge(20); 7 userBean.setName("test"); 8 userService.Say(userBean); 9 }
运行结果
Say com.muyi.service.impl.UsereServiceImpl UserBean{name='test', age=20, car=null} 开始 User被创建。。。。。UserBean{name='test', age=20, car=null} UserBean{name='testtest', age=20, car=null} 结束