2

I have a custom method annotation (@EventListener) that I use in a method inside a class that has the @Transactional annotation.

Below is a sample of the class

@Component
@Transactional
public class someClass {

    @EventListener
    public void someMethod() {

    }
}

The class is in a package include in the context files component scan. In another class which implements ApplicationContextAware, I check the methods of the classes if they have my @EventListener annotation. For some strange reason, when @Transactional is present in the class, my custom annotation is lost.

This is how I check for the method annotations:

public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

    System.out.println("SCANNING :::::: " + beanName);

    for (Method method : bean.getClass().getMethods()) {

        for(Annotation a : method.getAnnotations()) {
            System.out.println("\t>>>>> " + a.toString());
        }

    ... 

Is there a way to use @Transactional without it messing up with other method annotations in the class it annotates?

Edit: I found this after I posted Spring - @Transactional - What happens in background? - seems some sort of a proxy is created it would appear that this causes my annotations to "disappear". Is there a way to get a reference to the original class?

Community
  • 1
  • 1
jett
  • 947
  • 9
  • 27

1 Answers1

3

I found the ansewr to my question and posting it here in case anyone else has the same problem. Since @Transactional classes are proxied, I needed to get the original proxied class so I added the following:

    Class clazz;

    // if this was proxied by Spring, get the original class name
    clazz = AopUtils.getTargetClass(bean);
    if(clazz == null) {
        clazz = bean.getClass();
    }

    for (Method method : clazz.getMethods()) {

I used AopUtils.getTargetClass would get the original class, if it returned null it means that the class was not proxied so I just use bean.getClass()

jett
  • 947
  • 9
  • 27