Java 是否有可能达到bean方法';是从bean中的注释吗?
假设我正在使用以下代码初始化bean:Java 是否有可能达到bean方法';是从bean中的注释吗?,java,spring,annotations,javabeans,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; } } 我能从withing 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
annotation的信息吗
不是从
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);
}
}
你说的“某物”是什么意思?您的批注是运行时保留批注吗?MyBean
是否有任何关于MyConfig
的信息,或者您是否希望它知道注释而不知道它的名称?@realpoint(1)“something”表示注释存在及其参数。(2) 注释和所需的一样“好”,而且它肯定是运行时(3)no(4)我预计可能是Spring,当从注释配置实例化bean时,从注释中获取一些信息,bean可以访问它
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.
[]