0

I am trying to execute some code after one protected method inside abstract class gets called. It looks something like this.

abstract class SomeAbstractClass : ServiceOne, ServiceTwo {
  protected fun doSomething(p1: String, p2: Int): SomeEntity {
    // some business logic
    return SomeEntity()
  }
}

I want to create annotation class like the one below and annotate method (above) with it and I want it to execute after class method returns value. I tried this and many other variations but nothing worked for me.

@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
annotation class EntityCreated {
    @Aspect
    @Component
    class EntityAspect {
        @AfterReturning("@annotation(EntityCreated)")
        fun afterSuccessfulCreate(jp: JoinPoint) {
            // Created, execute something here
        }
    }
}
hrabrica
  • 89
  • 3
  • Feedback, please. Don't just ask questions but then not react to answers or comment, which is not very polite. Thank you. – kriegaex Oct 28 '21 at 12:10

1 Answers1

1

While protected methods are off limits for JDK proxies when proxying interfaces, the CGLIB proxies used by Spring to extend classes can intercept protected methods. But in order to proxy a Kotlin class, you have to open it, so it is not final and can be proxied.

Please note, however, that if you override a protected method in Java, that overridden method will not "inherit" the super method's annotations. This is a Java limitation and unrelated to AOP. Annotation inheritance only works from parent to sub classes, if the annotation bears the @Inherited meta annotation. There is a way to emulate annotation inheritance using an advanced form of a technique called ITD (inter-type definition) in native AspectJ, but not in simple Spring AOP.

The exact answer to your question depends on your exact use case, your sample code is too fragmentary to answer in more detail.

kriegaex
  • 63,017
  • 15
  • 111
  • 202