• Spring之AOP、execution和前置通知


    一、创建LogBefore.java文件:

    package org.ruangong.aop;
    
    import java.lang.reflect.Method;
    
    import org.springframework.aop.MethodBeforeAdvice;
    
    public class LogBefore implements MethodBeforeAdvice{
    
    	@Override
    	public void before(Method method, Object[] args, Object target) throws Throwable {
    		// TODO Auto-generated method stub
    		System.out.println("前置通知...");
    	}
    
    }
    

      二、配置applicationContext.xml文件:

    <!-- 前置通知 -->
    	<bean id="studentDao" class="org.ruangong.dao.impl.StudentDaoImpl"></bean>
    	
    	
    	<bean id="studentService" class="org.ruangong.service.StudentServiceImpl">
    		<property name="studentDao" ref="studentDao"></property>
    	</bean>
    	<!-- 通知类 -->
    	<bean id="logBefore" class="org.ruangong.aop.LogBefore"></bean>
    	<!-- 将addStudent()和通知进行关联 -->
    	<aop:config>
    	<!-- 配置切入点,在哪里执行通知 -->
    		<aop:pointcut expression="execution(public void org.ruangong.service.StudentServiceImpl.addStudent(org.ruangong.entity.Student))" id="pointcut"/>
    		<!-- 相当于连接切入点和切面的线 -->
    		<aop:advisor advice-ref="logBefore" pointcut-ref="pointcut"/>
    		<aop:aspect></aop:aspect>
    	</aop:config>
    

      三、进行测试:

    public static void testAOP(){
    		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    		IStudentService studentService= (IStudentService) context.getBean("studentService");
    		Student student = new Student();
    		student.setStuNo(123);
    		student.setStuName("李明");
    		student.setStuAge(36);
    		studentService.addStudent(student);
    	}
    

      

     如果想要在两个方法之前都执行前置通知,只需要在xml文件中,

    <aop:pointcut expression="execution(public void org.ruangong.service.StudentServiceImpl.deleteStudentByNo(int)) or execution(public void org.ruangong.service.StudentServiceImpl.addStudent(org.ruangong.entity.Student))" id="pointcut"/>
    

      添加execution()并用or连接。

  • 相关阅读:
    运维常见面试题
    python常见面试题
    常见面试题
    常用算法之‘归并排序’
    python库大全
    Springboot拦截器无效,解决办法
    Springboot 不返回页面,只反回文本
    SpringBoot 接收参数的几种常用方式(转载)
    mysql 查询每个分组的前几名
    Java中TimeZone类的常用方法
  • 原文地址:https://www.cnblogs.com/jccjcc/p/13982605.html
Copyright © 2020-2023  润新知