我使用@In注解使用Seam将bean注入到我的控制器中。注入的类有一个自定义注释,当调用injectedClass.getClass().getAnnotation(annotationClass)时,它返回null。
调试时,我发现Seam传递了一个代理实例,因此getClass()返回InjectedClass_$$_javassist_seam_5,它没有我的自定义注释。
我如何从代理类中获得我的自定义注解?
下面是我的类的样子:
@CustomAnnotation(value="myvalue")
@Name("myAnnotatedClass")
public class MyAnnotatedClass extends SuperClass {...}
@Scope(ScopeType.SESSION)
@Name("myController")
public class MyController {
@In("#{myAnnotatedClass}")
private MyAnnotatedClass myAnnotatedClass;
public void actionMethod(){
//call another class which call myAnnotatedClass.getClass().getAnnotation(CustomAnnotation.class)
//then do some reflection for MyAnnotatedClass fields
}
}发布于 2009-12-30 22:25:26
问得好。
当您使用Seam调用方法时,它会被代理截获。这个函数启用了“In”或“@Out-jection”。但此规则有一个例外:当您调用内部方法时,它不起作用。
所以试一下这段代码
@Name
public class Service {
@In
private MyAnnotatedClass myAnnotatedClass;
public void myInterceptedMethod() {
// internal method bypass interceptor
// So @In or @Out-jection is not enabled
internalMethod();
}
private void internalMethod() {
System.out.println(myAnnotatedClass.getClass().getAnnotation(annotationClass));
}
}添加到原始答案的
您希望从bean中检索注释。但是,由于方法拦截器,myAnnotatedClass.getClass()返回一个代理对象,而不是bean类本身。
对于每个bean类,Seam都会创建一个组件定义,其中存储在应用程序上下文中。该属性的名称遵循以下模式:组件名称加上.component。所以如果你有一个像这样的bean
@Name("myBean")
public class MyBean {
}它的组件定义存储在attribute myBean.component中
因此,在您的方法中,您可以使用
Component myBeanComponentDefinition = (Component) Context.getApplicationContext().get("myBean.component");现在您可以调用
myBeanComponentDefinition.getBeanClass().getAnnotation(CustomAnnotation.class);致以敬意,
发布于 2013-04-12 18:46:51
如果你想减少"ComponentDefinition“的过度膨胀,你也可以使用这个,它也适用于CDI和Spring:
Class.forName(myBean.getClass().getCanonicalName().substring(0,myBean.getClass().getCanonicalName().indexOf("$"))).getAnnotation(MyAnnotation.class)https://stackoverflow.com/questions/1979717
复制相似问题