2017-04-08 65 views
2

假设我初始化豆用下面的代码:是否可以从bean内部到达bean方法的注释?

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

我可以从withing豆构造或withing bean的方法讲讲@MyAnnotation注解知道吗?

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

+0

什么意思是“某事”?您的注释是运行时保留注释吗? “MyBean”是否有关于“MyConfig”的任何信息,或者您是否期望它知道注释而不知道是什么称呼它? – RealSkeptic

+0

@RealSkeptic(1)“something”意思是注解的存在和它的参数。 (2)注释和所需的一样“好”,它绝对是运行时(3)否(4)我期望可能是Spring,当从注释配置实例化bean时,从注释中获取一些信息, – Dims

回答

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. 
[] 
相关问题