使用Java反射提取注释值?

编程入门 行业动态 更新时间:2024-10-25 02:25:58
本文介绍了使用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.可能存在使用方法调用的其他解决方案,该方法调用使用 ClassUtils 来使该类位于代理接口的后面,但我并没有对此进行过多研究.

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反射提取注释值?

本文发布于:2023-11-11 18:38:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579252.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:注释   反射   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!