【问题标题】:Why findAnnotation or getAnnotation returns null?为什么 findAnnotation 或 getAnnotation 返回 null?
【发布时间】:2016-04-02 15:19:11
【问题描述】:

我正在用 sping3 编写一些 aop 代码。 这是我的注释。

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    String name() default "foo"
}

我为上面的注释设置了一个pointcut

<aop:pointcut id="service" expression="@annotation(com.foo.datasource.DataSource)" />
<aop:advisor advice-ref="dataSourceExchange" pointcut-ref="service" order="1"/>
<bean id="dataSourceExchange" class="com.foo.datasource.DataSourceExchange"/>

我写了一个服务方法,并给它加上了上面的注解。在服务之前调用的DataSourceExchange 类中,我尝试获取注解。

class DataSourceExchange implements MethodInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("Method name : "
                + invocation.getMethod().getName());
        System.out.println("Method arguments : "
                + Arrays.toString(invocation.getArguments()));

        DataSource dataSource = AnnotationUtils.findAnnotation(invocation.getMethod(), DataSource.class);
        System.out.println(dataSource);

我正确地得到了方法的名称。 但是注解dataSource 只是返回null。 有什么问题?我认为我调用的服务方法肯定是注解的,否则不会触发pointcut

【问题讨论】:

    标签: java spring-3


    【解决方案1】:

    我终于通过使用解决了这个问题 Method realMethod = invocation.getThis().getClass().getDeclaredMethod(proxyedMethod.getName(), proxyedMethod.getParameterTypes());找出真正的方法。

    更多详情,请查看Alter dataSource in Spring By AOP And Annotation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-26
      • 1970-01-01
      • 2016-12-28
      • 2015-11-25
      • 2015-07-04
      • 2019-09-29
      • 2015-02-25
      • 2015-10-21
      相关资源
      最近更新 更多