(1)Aspect(切面):通常是一个类,里面可以定义切入点和通知
(2)JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用
(3)Advice(通知):AOP在特定的切入点上执行的增强处理,有before,after,afterReturning,afterThrowing,around
(4)Pointcut(切入点):就是带有通知的连接点,在程序中主要体现为书写切入点表达式
(5)AOP代理:AOP框架创建的对象,代理就是目标对象的加强。
创建接口 IStudentDao.java
package com.zy.dao; public interface IStudentDao { void addStudent(String msg); }创建接口实现 StudentDaoImpl.java 这里知识模拟数据库操作,没有连接数据库了。
package com.zy.dao.impl; import com.zy.dao.IStudentDao; public class StudentDaoImpl implements IStudentDao{ @Override public void addStudent(String msg) { System.out.println("添加学生:"+msg); } }创建接口IStudentService.java
package com.zy.service; public interface IStudentService { void addStudent(String msg); }接口实现StudentServiceImpl.java
package com.zy.service.impl; import javax.annotation.Resource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.zy.dao.IStudentDao; import com.zy.service.IStudentService; public class StudentServiceImpl implements IStudentService{ IStudentDao studentDao; public void setStudentDao(IStudentDao studentDao) { this.studentDao = studentDao; } @Override public void addStudent(String msg) { studentDao.addStudent(msg); } }需要在执行Service层的addStudent()方法之前执行(这是前置增强,需要实现MethodBeforeAdvice接口)
创建BeforeAop.java
package com.zy.aop; import java.lang.reflect.Method; import org.springframework.aop.MethodBeforeAdvice; public class BeforeAop implements MethodBeforeAdvice{ // method : 切入的方法 <br> // args :切入方法的参数 <br> // target :目标对象 @Override public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("-----接口前置增强5555-----"); System.out.println("method:"+method.getName()+"\nargs:"+args.length+"\ntarget:"+target.getClass()); } }创建StudentTest.java
package com.zy.test; import java.applet.AppletContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.zy.service.IStudentService; public class StudentTest { public static void main(String[] args) { testAop(); // testDelStuAop() ; } // 增加学生的AOP测试 private static void testAop() { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); IStudentService studentService = (IStudentService) ac.getBean("studentService"); studentService.addStudent("学生1"); } }通过接口实现前置可以拿到 method : 切入的方法 args :切入方法的参数 target :目标对象