Search code examples
javajakarta-eejava-ee-6

Determine BMT or CMT


Environment: Java EE 6

How to determine in Interceptor if the invoked bean is container managed (CMT) or bean managed (BMT)?


Solution

  • Beans are by definition always container managed.

    Likely you want to know is current transaction CMT or BMT. Because @AroundInvoke interceptor method is executed in same transaction as intercepted business method, you can check transaction type with following:

    public class SomeInterceptor {
        @Resource
        private javax.ejb.SessionContext sessionContext;
    
        @AroundInvoke
        public Object intercept(InvocationContext ctx) throws Exception {
            if (isCMT()) {
    
            }
            ...
        }
    
        private boolean isCMT() {
            try {
               //throws IllegalStateException if not BMT
               sessionContext.getUserTransaction();
               return false;
            }
            catch (IllegalStateException ise) {
               return true;
            }
        }
    }
    

    Of course using exceptions to control flow is bad, but I am not aware of alternative method to differentiate between BMT and CMT.