是否有可能从bean中获取bean方法的注释?

时间:2017-04-08 12:42:11

标签: java spring annotations javabeans

假设我使用以下代码初始化bean:

@Configuration 
MyConfig {
    @Bean
    @MyAnnotation // how to know this from bean constructor or method?
    MyBean myBean() {
       MyBean ans = new MyBean();
       /// setup ans
       return ans;
    }
}

我可以通过使用bean构造函数或使用bean的方法来了解@MyAnnotation注释的内容吗?

不是来自myBean()方法,这是显而易见的。

1 个答案:

答案 0 :(得分:1)

它可能不是最好的甚至是正确的方式,但我的第一个猜测是使用当前的堆栈跟踪,它似乎对我有用:

package yourpackage;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AspectJRawTest {

    public static void main(String[] args) {
        System.out.println("custom annotation playground");

        ISomething something = new SomethingImpl();

        something.annotatedMethod();
        something.notAnnotatedMethod();
    }

}

interface ISomething {
    void annotatedMethod();

    void notAnnotatedMethod();
}

class SomethingImpl implements ISomething {
    @MyCustomAnnotation
    public void annotatedMethod() {
        System.out.println("I am annotated and something must be printed by an advice above.");
        CalledFromAnnotatedMethod ca = new CalledFromAnnotatedMethod();
    }

    public void notAnnotatedMethod() {
        System.out.println("I am not annotated and I will not get any special treatment.");
        CalledFromAnnotatedMethod ca = new CalledFromAnnotatedMethod();
    }
}

/**
 * Imagine this is your bean which needs to know if any annotations affected it's construction
 */
class CalledFromAnnotatedMethod {
    CalledFromAnnotatedMethod() {
        List<Annotation> ants = new ArrayList<Annotation>();
        for (StackTraceElement elt : Thread.currentThread().getStackTrace()) {
            try {
                Method m = Class.forName(elt.getClassName()).getMethod(elt.getMethodName());
                ants.addAll(Arrays.asList(m.getAnnotations()));
            } catch (ClassNotFoundException ignored) {
            } catch (NoSuchMethodException ignored) {
            }
        }
        System.out.println(ants);
    }
}

输出清楚地表明,当从对象的方法调用它时,我可以访问对象构造函数中的注释:

custom annotation playground
I am annotated and something must be printed by an advice above.
[@yourpackage.MyCustomAnnotation(isRun=true)]
I am not annotated and I will not get any special treatment.
[]