简体   繁体   English

在Java中创建自定义注释,并在调用方法时使用它

[英]Create custom annotation in Java and use it when a method is called

What I want to do is to create a custom annotation to use it on a Service, and each time a method is called from there first execute something. 我想做的是创建一个自定义批注以在Service上使用它,并且每次从那里调用方法时都首先执行一些操作。 For example: 例如:

@CustomAnnotation
public Class MyService{

   public void myMethod(){
      //do something
   }
}

And when myMethod is called, do something before its code is executed, and then do what it has to do. 并且在调用myMethod时,请在执行其代码之前执行一些操作,然后执行其必须执行的操作。 Is there any way to do that? 有什么办法吗? I need to do it with annotations, using interfaces or inheritance for that is useless because is for each method, not just one. 我需要做注释,使用接口或继承是没有用的,因为它适用于每种方法,而不仅仅是一种方法。

I know how to scan a package to get the classes annotated, but I don't know how to check it at runtime when the app is running. 我知道如何扫描软件包以对类进行注释,但是我不知道如何在应用程序运行时在运行时检查它。

Thank you! 谢谢!

It seems that what you need may be achieved by using AOP (aspect oriented programming). 似乎可以通过使用AOP(面向方面​​的编程)来实现所需的功能。

Ive posted the code example here . 我已经在这里发布了代码示例。 It executes some code before the annotated methods and doesn't execute for others. 它在带注释的方法之前执行一些代码,而对其他方法则不执行。

AOP allows you to do that without intervention in code of method-containing classes, you may alter methods behavior without altering methods themselves and their invocation code. AOP允许您在不干预包含方法的类的代码的情况下执行此操作,您可以在不更改方法本身及其调用代码的情况下更改方法的行为。 You may even skip method execution using this technique (using @Around advice). 您甚至可以跳过使用该技术的方法执行(使用@Around建议)。 It is useful if you need security checks before allowing method execution, for example. 例如,如果在允许方法执行之前需要安全检查,这将很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM