有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring使用java反射提取注释值?

我有以下课程

我在服务类中将someDao自动连接为@Autowired SomeDao someDao。 我将服务中的逻辑称为someDao.getName(2);

一些服务impl。爪哇

public class SomeServiceImpl{

@Autowired SomeDao someDao
//call dao methods using someDao
}

萨梅达奥。爪哇

public  interface SomeDao{

 String getName(Int id);
}

有点奇怪。爪哇

public class SomeDaoImpl implements SomeDao{

 @CustomAnnotation("somevalue")
 public String getName(int id){
   //logic

  }


}

某个方面。爪哇

@Around("execution(public * *(..)) && @annotation(com.mycompany.CustomAnnotation)")
    public Object procedeNext(ProceedingJoinPoint call) throws Throwable {

  //Access annotation value
        MethodSignature signature = (MethodSignature) call.getSignature();
        Method method = signature.getMethod();
        CustomAnnotation myAnnotation =   method.getAnnotation(CustomAnnotation.class);
        String name = myAnnotation.value();
            //here i am expecting name value "somevalue" but it is returning null


}

CustomAnnotation@Retention(RetentionPolicy.RUNTIME)

在上述方面,String name = myAnnotation.value();应该给我somevalue,但它给了null。有什么建议吗?但若我将@CustomAnnotation("somevalue")保留在接口中,那个么它就会给出值。注释接口方法好吗


共 (1) 个答案

  1. # 1 楼答案

    这是因为默认的spring APO代理从接口而不是类获取方法。因此,当方法调用来自接口而不是类时

    您有几个选择:

    一,。要么将xml配置更改为<aop:config proxy-target-class="true">,它应该可以工作,因为代理将获取类而不是接口。如果您有多个XMLAOP配置,并且其中一个以目标类为目标,那么所有这些配置都将执行相同的操作,因此请小心

    二,。或者您坚持使用默认值,然后在界面上添加注释。只要你小心你的注释,这是非常好的。特别是如果你有交易

    三,。可能还有其他解决方案使用方法调用来获取目标类,使用ClassUtils来获取代理接口后面的类,但我没有对此做太多研究

    希望这有帮助