我正在用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
。
答案 0 :(得分:0)
我终于通过使用解决了这个问题
Method realMethod = invocation.getThis().getClass().getDeclaredMethod(proxyedMethod.getName(), proxyedMethod.getParameterTypes())
;找出真正的方法。