使用Java反射提取注释值? [英] Extracting the annotation value using java reflection?

查看:64
本文介绍了使用Java反射提取注释值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程.

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

I autowired someDao in service class as @Autowired SomeDao someDao. I call the logic in service as someDao.getName(2);

public class SomeServiceImpl{

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

SomeDao.java

public  interface SomeDao{

 String getName(Int id);
}

SomeDaoImpl.java

public class SomeDaoImpl implements SomeDao{

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

  }


}

SomeAspect.java

@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"),那么它会带来价值.注释接口方法好吗?

In above aspect, String name = myAnnotation.value(); should give me somevalue but it is giving null. Any suggestion? But if I keep @CustomAnnotation("somevalue") in interface then it gives value. Is it good to annotate interface methods?

推荐答案

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

It's because the default spring APO proxy gets the methods from the interface and not the class. So when the method call is the one from the interface and not the class.

您有几种选择:

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

1.either you change your xml configuration to <aop:config proxy-target-class="true"> and it should work since the proxy will get the class and not the interface. If you have several xml aop config, and if one of them targets the target class then all of them will do the same so be careful.

2.或者您坚持使用默认值,然后将注释放在界面上.只要注意注释,该方法就可以很好地工作.尤其是如果您有交易.

2.Or you stick with the default and then you put your annotations on the interface. That works perfectly fine as long as you are careful with your annotations. Especially if you have transactions.

3.可能存在使用方法调用的其他解决方案,该方法调用使用

3.There might be an other solution using the method call to get the target class using ClassUtils to get the class behind the proxyed interface, but I did not look to much into it.

希望这会有所帮助

这篇关于使用Java反射提取注释值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆