简体   繁体   English

Spring修改由自定义批注标记的任何类的字段

[英]Spring Modify a field of any class that marked by a custom annotation

I want to mark a field of a class with my custom annotation. 我想用我的自定义注释标记一个类的字段。 And whenever any method is invoke I want to do some modification on that field. 每当调用任何方法时,我都希望对该字段进行一些修改。

public class Message{
    public Integer id;

    @FreeText   // this is my custom annotation 
    public String htmlMsg;
    public String textMsg ;
 }

This annotation (@FreeText) can be used in any class. 该注释(@FreeText)可以在任何类中使用。 In seasar framework, I can do this by create an interceptor and override invoke method. 在seasar框架中,我可以通过创建一个拦截器并重写invoke方法来做到这一点。 The I can get the object of this class and the find the field that marked with my annotation and modify it. 我可以获取此类的对象,并找到标有我的注释的字段并进行修改。 However, i cannot find a way to do it in Spring. 但是,我找不到在春季进行的方法。 In spring, I found some method like MethodInvocationInterceptor, but I don't know how to implement it. 在春季,我发现了诸如MethodInvocationInterceptor之类的方法,但是我不知道如何实现它。 Can you suggest any way to do this in Spring? 您能在春季建议任何方法吗?

Seasar2 and Spring are very close. Seasar2和Spring非常接近。 I have not tested but you can do something like this. 我没有测试过,但是您可以做这样的事情。 First create FreeText custom annotation 首先创建FreeText自定义注释

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface FreeText {}

Then create the following interceptor 然后创建以下拦截器

public class EncryptSensitiveDataInterceptor extends MethodInterceptor {
@Override
public Object invoke(MethodInvocation in) throws Throwable {

    Object[] params = in.getArguments();

    Object param = params[0];
    for (Field field : param.getClass().getDeclaredFields()) {
        for (Annotation anno : field.getDeclaredAnnotations()) {
            if (anno instanceof FreeText) {
              field.set(param, [YOUR CUSTOM LOGIC METHOD]);
     }

  }
 }
  return in.proceed();
}

Hope this help. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM