注解底层是怎么实现业务逻辑的
通过以下例子来解释:
- 首先写一个接口并实现这个接口
//随便建一个接口,这里就写一个UserService
public interface UserService {
int addUser() throws InterruptedException;
}
//然后实现UserService接口,并随意写一些方法用来测试
public class UserServiceImpl implements UserService {
@Override
public int addUser() throws InterruptedException {
Thread.sleep(2000);
System.out.println("1、开始添加用户");
System.out.println("2、结束添加用户");
addLog();
return 0;
}
@ExtAnno
public void addLog() throws InterruptedException {
Thread.sleep(3000);
System.out.println("记录日志");
}
}
- 自定义一个注解,没有什么意义,就是很随意的
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface ExtAnno {
}
- 写一个类实现InvocationHandler接口,实现其中的方法,用来实现注解中需要的业务逻辑
public class TestInvocationHandler implements InvocationHandler {
/**
* 目标对象
*/
private Object target;
public TestInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// System.out.println("对目标方法的增强代码");
Method method1 = target.getClass().getMethod(method.getName(), method.getParameterTypes());
ExtAnno extAnno = method1.getAnnotation(ExtAnno.class);
if (extAnno == null) {
return method.invoke(target, args);
}
new Thread(new Runnable() {
@Override
public void run() {
try {
method.invoke(target, args);//执行目标方法
} catch (Exception e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* 生成代理对象方法
*
* @param <T>
*/
public <T> T getProxy() {
return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
}
}
- 写一个类测试一下自定义的注解是否成功
public class Test {
public static void main(String[] args) throws InterruptedException {
//被代理对象
UserServiceImpl userService = new UserServiceImpl();
TestInvocationHandler invocationHandler = new TestInvocationHandler(userService);
//代理对象
UserService proxy = invocationHandler.getProxy();
proxy.addUser();
}
}
输出结果:
1、开始添加用户
2、结束添加用户
记录日志