手动代理
JDK动态代理
IStudentService.java
1 package com.gyf.service;
2
3 public interface IStudentService {
4
5 //切面编程
6 public void addStudent();
7
8 public void updateStudent();
9
10 public int deleteStudent(int id);
11
12 }
StudentServiceImpl.java
1 package com.gyf.service;
2
3 public class StudentServiceImpl implements IStudentService {
4 @Override
5 public void addStudent() {
6 System.out.println("添加学生信息。。。");
7
8 }
9
10 @Override
11 public void updateStudent() {
12 System.out.println("更新学生信息。。。");
13 }
14
15 @Override
16 public int deleteStudent(int id) {
17 System.out.println("通过id删除用户。。。");
18 return 1;
19 }
20 }
MyAspect.java
1 package com.gyf.service;
2
3 /**
4 * 切面类:增强代码与切入点 结合
5 */
6 public class MyAspect {
7
8 public void before(){
9 System.out.println("开启事务。。。");
10 }
11 public void after(){
12 System.out.println("提交事务。。。");
13 }
14 }
StudentServiceFactory.java
1 package com.gyf.service;
2
3 import java.lang.reflect.InvocationHandler;
4 import java.lang.reflect.Method;
5 import java.lang.reflect.Proxy;
6
7 public class StudentServiceFactory {
8
9 public static IStudentService creatStudentService(){
10 //1.创建目标对象
11 IStudentService studentService = new StudentServiceImpl();
12 //2.声明切面类对象
13 MyAspect aspect = new MyAspect();
14 //3.把切面类2个方法应用目标类
15 //3.1 创建JDK代理
16 IStudentService proxyStudentService = (IStudentService) Proxy.newProxyInstance(
17 StudentServiceFactory.class.getClassLoader(),
18 studentService.getClass().getInterfaces(),
19 new InvocationHandler() {
20 @Override
21 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
22 //开启事务
23 aspect.before();
24
25 Object retObj = method.invoke(studentService, args);
26
27 //提交事务
28 aspect.after();
29 //返回值是业务方法的返回值
30 return retObj;
31 }
32 });
33
34 return proxyStudentService;
35 }
36
37 }
main.java
1 package com.gyf.test;
2
3 import com.gyf.service.IStudentService;
4 import com.gyf.service.StudentServiceFactory;
5 import org.junit.Test;
6
7 public class ProxyAspectTest {
8
9 @Test
10 public void test(){
11 //自定义实现AOP编程,使用JDK代理来实现
12 IStudentService studentService = StudentServiceFactory.creatStudentService();
13 studentService.deleteStudent(10);
14 studentService.addStudent();
15 studentService.updateStudent();
16 }
17 }
=================================
结果:
开启事务。。。
通过id删除用户。。。
提交事务。。。
开启事务。。。
添加学生信息。。。
提交事务。。。
开启事务。。。
更新学生信息。。。
提交事务。。。