In Python, there is the concept of a decorator, which wraps the execution of a method with some behavior. Is it possible to implement this in Java?

For example, there are many methods, each of which opens a Hibernate session that either performs and closes the session. To avoid repeating the code for working with sessions, I would like to bring this all to the decorator, in which the session is opened accordingly, the main method is called, then the session is closed.

For now, the only thought is to implement your own annotation, and specify it in the necessary methods. However, it is not clear whether it is possible to add such behavior to the annotation, since all the examples I found are based on reflection and the need to explicitly indicate the class with which the annotation should be processed, and it is not known in advance how many such classes and methods are.

  • Tried to search? ru.wikipedia.org/wiki/… - Sergey Mitrofanov
  • This option is not suitable, since it introduces a restriction on the namespace of methods - carapuz

1 answer 1

I guess you are looking for AOP. There are two common libraries - Spring AOP and AspectJ. What suits you best - you can read and choose

habrahabr.ru/post/114649

springbyexample.com.ua/2012/10/spring-aop-aspectj.html