一、创建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连接。