gpt4 book ai didi

java - 是否可以从 bean 中获取 bean 方法的注解?

转载 作者:行者123 更新时间:2023-11-30 10:31:17 26 4
gpt4 key购买 nike

假设我正在使用以下代码初始化 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 bean 构造函数或 withing 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.
[]

关于java - 是否可以从 bean 中获取 bean 方法的注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43294226/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com