代理模式(Proxy)是通过代理对象访问目标对象,这样可以在目标对象基础上增强额外的功能,如添加权限,访问控制和审计等功能。
1.自定义业务接口
package com.haijiao12138.demo.spring.agentLog0815;
public interface BusinessClassService {
public void doSomeThing();//自定义接口
}
2.自定义业务接口实现类
package com.haijiao12138.demo.spring.agentLog0815;
public class BusinessClassServiceImpl implements BusinessClassService {
//执行某事
@Override
public void doSomeThing() {
System.out.println("doing somthing......");
}
}
3.日志接口和实现类
package com.haijiao12138.demo.spring.agentLog0815;
import java.lang.reflect.Method;
public interface MyLogger {
//记录进入方法时间
public void saveIntoMethodTime(Method method);
//记录退出方法的时间
public void saveOutMethodTime(Method method);
}
package com.haijiao12138.demo.spring.agentLog0815;
import java.lang.reflect.Method;
import java.util.Date;
public class MyLoggerImpl implements MyLogger{
@Override
public void saveIntoMethodTime(Method method) {
System.out.println("进入" + method.getName() +"方法时间为: " + new Date());
}
@Override
public void saveOutMethodTime(Method method) {
System.out.println("退出" + method.getName() + "方法时间为:" + new Date());
}
}
4.下面是日志类的handler实现:
package com.haijiao12138.demo.spring.agentLog0815;
import java.lang.reflect.Method;
import java.util.Date;
public class MyLoggerImpl implements MyLogger{
@Override
public void saveIntoMethodTime(Method method) {
System.out.println("进入" + method.getName() +"方法时间为: " + new Date());
}
@Override
public void saveOutMethodTime(Method method) {
System.out.println("退出" + method.getName() + "方法时间为:" + new Date());
}
}
5.测试类
package com.haijiao12138.demo.spring.agentLog0815;
import java.lang.reflect.Proxy;
public class MyLoggerTest {
public static void main(String[] args) {
BusinessClassService businessClassService = new BusinessClassServiceImpl();
MyLoggerHandler myLoggerHandler = new MyLoggerHandler(businessClassService);
BusinessClassService businessClass = (BusinessClassService) Proxy.newProxyInstance(businessClassService.getClass().getClassLoader(), businessClassService.getClass().getInterfaces(),myLoggerHandler);
businessClass.doSomeThing();
}
}
结果输出:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。