Java 无xml配置的非Spring轻量级AOP,用于将注释编织到方法

Java 无xml配置的非Spring轻量级AOP,用于将注释编织到方法,java,annotations,aop,Java,Annotations,Aop,需要在某些注释上运行before和after方法 没有使用spring,没有xml。是否可能有某种我从main()设置的AOP引擎,以便在需要时调用它?我也可以输入一个方法来手动调用一个评估方法 例如: public void doThis(@RequiredSecurityRole("admin") user){ doAOPStuff(); } before() after()将操作登录到数据库中 如何实现这一点?您可以使用java.lang.reflect.Proxy类自己实现这一

需要在某些注释上运行before和after方法

没有使用spring,没有xml。是否可能有某种我从main()设置的AOP引擎,以便在需要时调用它?我也可以输入一个方法来手动调用一个评估方法

例如:

public void doThis(@RequiredSecurityRole("admin") user){
    doAOPStuff();
}
before()

after()
将操作登录到数据库中


如何实现这一点?

您可以使用java.lang.reflect.Proxy类自己实现这一点。它确实要求在接口中定义要代理的代码

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DoItYourAop {

  public static void main(String[] args) {
    SaysHello saysHello = new SaysHelloImpl();
    InvocationHandler logger = new LoggingProxy(saysHello);
    SaysHello proxy = (SaysHello) Proxy.newProxyInstance(SaysHello.class.getClassLoader(),
        new Class[]{SaysHello.class}, logger);
    proxy.sayHello();
  }

  public interface SaysHello {

    void sayHello();

    void sayGoodbye();
  }

  public static class SaysHelloImpl implements SaysHello {
    @Log
    @Override
    public void sayHello() {
      System.out.println("Says Hello");
    }

    @Override
    public void sayGoodbye() {
      System.out.println("Says Goodbye");
    }
  }

  @Retention(RUNTIME)
  @interface Log {
  }

  public static class LoggingProxy implements InvocationHandler {

    private final Object proxied;

    public LoggingProxy(Object proxied) {
      this.proxied = proxied;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      Method proxiedMethod = proxied.getClass().getMethod(method.getName(), method.getParameterTypes());
      boolean log = proxiedMethod.isAnnotationPresent(Log.class);
      if (log) {
        System.out.println("Before");
      }

      Object result = method.invoke(proxied, args);

      if (log) {
        System.out.println("After");
      }

      return result;
    }
  }
}