springspring-bootsessionspring-sessionsessioncontext

What is the replacement of EJB SessionContext object in spring boot?


I am migrating an EJB project to Spring boot project. I have successfully replaced other annotations to the spring annotation, but havving problem with SessionContext object. My legacy code is bellow

@Resource
SessionContext sessionContext;
.....
if (some condition) {
    sessionContext.setRollbackOnly();
    return false;
}

For this code i am getting the following error

A component required a bean of type 'javax.ejb.SessionContext' that could not be found.


Action:

Consider defining a bean of type 'javax.ejb.SessionContext' in your configuration.


Solution

  • I think you'll have to use a few different functionalities.

    setRollbackOnly()

    Most often I have seen Session Context used for Rollbacks. In Spring, you can replace this with:

    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
    

    or annotate class with

    @Transactional(rollbackFor = MyException.class) 
    

    so you can throw your exception from class to cause rollback.

    getBusinessObject()

    The second most commonly used feature is method to load a business object so that I can, for example, create a new transaction within a same bean. In this case you can use Self-inject:

    @Lazy private final AccountService self;
    

    and annote method with @Transactional. This, of course, solves any other cases where you need to use the power of a proxy object.

    Other functionality is provided by other classes in Spring, but I think that these two are the most commonly used in the Java EE world and when migrating, one will look to replace them in Spring.