Create custom annotations with lifecycle hooks
masterYou can extend Forest by defining custom annotations and implementing a MethodAnnotationLifeCycle. This allows you to intercept the request lifecycle (e.g., onInvokeMethod, beforeExecute, onMethodInitialized) to perform tasks like custom signature encryption.
1. Define the Annotation:
Use @MethodLifeCycle to link the annotation to its handler class.
@Documented
@MethodLifeCycle(MyAuthLifeCycle.class)
@RequestAttributes
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface MyAuth {
String username();
String password();
}2. Implement the Lifecycle Class:
Implement MethodAnnotationLifeCycle<AnnotationType, ReturnType> to handle the logic.
public class MyAuthLifeCycle implements MethodAnnotationLifeCycle<MyAuth, Object> {
@Override
public void onInvokeMethod(ForestRequest request, ForestMethod method, Object[] args) {
System.out.println("Invoke Method '" + method.getMethodName() + "' Arguments: " + args);
}
@Override
public boolean beforeExecute(ForestRequest request) {
String username = (String) getAttribute(request, "username");
String password = (String) getAttribute(request, "password");
String basic = "MyAuth " + Base64Utils.encode("{" + username + ":" + password + "}");
request.addHeader("MyAuthorization", basic);
return true;
}
@Override
public void onMethodInitialized(ForestMethod method, MyAuth annotation) {
// Initialization logic
}
}3. Use the Annotation:
@Get("/hello/user?username={username}")
@MyAuth(username = "{username}", password = "bar")
String send(@DataVariable("username") String username);