假设我正在使用以下代码初始化 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()
方法内部,这是显而易见的。
好吧,这可能不是最好甚至正确的方法,但我的第一个猜测是使用当前的堆栈跟踪,它似乎对我有用:
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.
[]