我想知道的是“所有的类/方法Spring http://en.wikipedia.org/wiki/Spring_Framework注释为@Versioned的bean。
我创建了自定义注释,
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Versioned {
.....
}
这个注释完美运作当我使用 Java 反射来查找方法时:
for(Method m: obj.getClass().getMethods()){
if(m.isAnnotationPresent(Versioned.class)){
.... // Do something
}
但当我访问 Spring beans 并尝试类似的检查时它不起作用:
public class VersionScanner implements ApplicationContextAware{
public void setApplicationContext(ApplicationContext applicationContext){
for(String beanName: applicationContext.getBeanDefinitionNames()){
for(Method m: applicationContext.getBean(beanName).getClass().getDeclaredMethods()){
if(m.isAnnotationPresent(Versioned.class){
// This is not WORKING as expected for any beans with method annotated
}
}
}
}
}
事实上,这段代码确实找到了其他注解,例如@RequestMapping。我不确定我的自定义注释做错了什么。
通过查看您的代码,我发现您正在使用 Spring AOP 和 CGLIB 代理。由于您的类(其方法注释为@Versioned
)正在被代理。
我已经用您的代码库测试了这个解决方案。
使用以下代码,它应该可以解决您的问题。在代码片段下方查找更多选项:
@Configuration
public class VersionScanner implements ApplicationContextAware {
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
for (String beanName : applicationContext.getBeanDefinitionNames()) {
Object obj = applicationContext.getBean(beanName);
/*
* As you are using AOP check for AOP proxying. If you are proxying with Spring CGLIB (not via Spring AOP)
* Use org.springframework.cglib.proxy.Proxy#isProxyClass to detect proxy If you are proxying using JDK
* Proxy use java.lang.reflect.Proxy#isProxyClass
*/
Class<?> objClz = obj.getClass();
if (org.springframework.aop.support.AopUtils.isAopProxy(obj)) {
objClz = org.springframework.aop.support.AopUtils.getTargetClass(obj);
}
for (Method m : objClz.getDeclaredMethods()) {
if (m.isAnnotationPresent(Versioned.class)) {
//Should give you expected results
}
}
}
}
}
要检测代理类:
- 对于使用任何代理机制的 Spring AOP 代理,请使用
org.springframework.aop.support.AopUtils#isAoPProxy
- 如果您使用 Spring CGLIB 进行代理(而不是通过 Spring AOP),请使用
org.springframework.cglib.proxy.Proxy#isProxyClass
- 如果您使用 JDK Proxy 进行代理,请使用
java.lang.reflect.Proxy#isProxyClass
我刚刚写了一篇if
满足您的情况的条件;但如果使用多个代理实用程序,则多个if-else
必须根据上述信息编写条件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)