利用Proxy实现AOP的功能:
采用Proxy类方法,基本流程为:主函数->代理->目标对象的方法。对Proxy类有一个使用前提,就是目标对象必须要实现接口,否则不能使用这个方法。实现AOP的步骤如下:
- 创建接口: StudentInterface.java
- 创建接口实现类: Student.java
- 创建代理工厂类: ProxyFactory.java
1. 创建接口: StudentInterface.java
public interface StudentInterface {
public void print();
}
2. 创建接口实现类: Student.java
public class Student implements StudentInterface{
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print() {
System.out.println("Hello World");
}
}
3. 创建代理工厂类: ProxyFactory.java
public class ProxyFactory implements InvocationHandler {
private Object stu;
public Object createStudentProxy(Object stu){
this.stu = stu;
return Proxy.newProxyInstance(stu.getClass().getClassLoader(), stu.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Student s = (Student) stu;
Object object = null;
if(s.getName() != null){
object = method.invoke(stu, args);
}else {
System.out.println("Empty name. Proxy class takes interception");
}
return object;
}
}
总结:
- 目标对象必须实现接口。
- 返回创建的代理对象。
- 重写invoke()方法。
- 限制条件放在invoke()方法中。
利用CGLib实现AOP功能
CGLib(Code Generation Library)是一个开源项目,它是一个强大的,高性能,高质量的Code生成类库,它可以在运行期扩展Java类与实现Java接口。实现AOP功能的步骤如下所示:
- 引入相关的Maven
- 创建实体类
- 创建CGLib代理类
- 创建入口类进行测试
1. 引入相关的Maven
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.3.0</version>
</dependency>
2.创建实体类
public class Student{
private String name;
public Student() {
}
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print() {
System.out.println("Hello World");
}
}
3. 创建CGLib代理类
public class ProxyFactory implements InvocationHandler {
private Object stu;
public Object createStudentProxy(Object stu){
this.stu = stu;
return Proxy.newProxyInstance(stu.getClass().getClassLoader(), stu.getClass().getInterfaces(), this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Student s = (Student) stu;
Object object = null;
if(s.getName() != null){
object = method.invoke(stu, args);
}else {
System.out.println("Empty name. Proxy class takes interception");
}
return object;
}
}
4.创建入口类进行测试
public class Main {
public static void main(String[] args) {
Student s1
= (Student)(new CGLibProxyFactory()).createStudent(new Student());
Student s2
= (Student)(new CGLibProxyFactory()).createStudent(new Student("Lemon"));
s1.print();
s2.print();
}
}
使用CGLib和Proxy的区别:
Proxy实现的代理对象和目标对象必须实现接口。使用CGLib不需要实现接口。