Spring @Transaction method call by the method within the same class, does not work?

JavaSpringAspectjSpring Aop

Java Problem Overview


I am new to Spring Transaction. Something that I found really odd, probably I did understand this properly.

I wanted to have a transactional around method level and I have a caller method within the same class and it seems like it does not like that, it has to be called from the separate class. I don't understand how is that possible.

If anyone has an idea how to resolve this issue, I would greatly appreciate. I would like to use the same class to call the annotated transactional method.

Here is the code:

public class UserService {

	@Transactional
	public boolean addUser(String userName, String password) {
		try {
			// call DAO layer and adds to database.
		} catch (Throwable e) {
			TransactionAspectSupport.currentTransactionStatus()
					.setRollbackOnly();

		}
	}

	public boolean addUsers(List<User> users) {
		for (User user : users) {
			addUser(user.getUserName, user.getPassword);
		}
	} 
}

Java Solutions


Solution 1 - Java

It's a limitation of Spring AOP (dynamic objects and cglib).

If you configure Spring to use AspectJ to handle the transactions, your code will work.

The simple and probably best alternative is to refactor your code. For example one class that handles users and one that process each user. Then default transaction handling with Spring AOP will work.


Configuration tips for handling transactions with AspectJ

To enable Spring to use AspectJ for transactions, you must set the mode to AspectJ:

<tx:annotation-driven mode="aspectj"/>

If you're using Spring with an older version than 3.0, you must also add this to your Spring configuration:

<bean class="org.springframework.transaction.aspectj
        .AnnotationTransactionAspect" factory-method="aspectOf">
    <property name="transactionManager" ref="transactionManager" />
</bean>

Solution 2 - Java

In Java 8+ there's another possibility, which I prefer for the reasons given below:

@Service
public class UserService {

    @Autowired
    private TransactionHandler transactionHandler;

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            transactionHandler.runInTransaction(() -> addUser(user.getUsername, user.getPassword));
        }
    }

    private boolean addUser(String username, String password) {
        // TODO call userRepository
    }
}

@Service
public class TransactionHandler {

    @Transactional(propagation = Propagation.REQUIRED)
    public <T> T runInTransaction(Supplier<T> supplier) {
        return supplier.get();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public <T> T runInNewTransaction(Supplier<T> supplier) {
        return supplier.get();
    }
}

This approach has the following advantages:

  1. It may be applied to private methods. So you don't have to break encapsulation by making a method public just to satisfy Spring limitations.

  2. Same method may be called within different transaction propagations and it is up to the caller to choose the suitable one. Compare these 2 lines:

    transactionHandler.runInTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

    transactionHandler.runInNewTransaction(() -> userService.addUser(user.getUserName, user.getPassword));

  3. It is explicit, thus more readable.

Solution 3 - Java

The problem here is, that Spring's AOP proxies don't extend but rather wrap your service instance to intercept calls. This has the effect, that any call to "this" from within your service instance is directly invoked on that instance and cannot be intercepted by the wrapping proxy (the proxy is not even aware of any such call). One solutions is already mentioned. Another nifty one would be to simply have Spring inject an instance of the service into the service itself, and call your method on the injected instance, which will be the proxy that handles your transactions. But be aware, that this may have bad side effects too, if your service bean is not a singleton:

<bean id="userService" class="your.package.UserService">
  <property name="self" ref="userService" />
    ...
</bean>

public class UserService {
    private UserService self;
    
    public void setSelf(UserService self) {
        this.self = self;
    }

    @Transactional
    public boolean addUser(String userName, String password) {
        try {
        // call DAO layer and adds to database.
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus()
                .setRollbackOnly();

        }
    }

    public boolean addUsers(List<User> users) {
        for (User user : users) {
            self.addUser(user.getUserName, user.getPassword);
        }
    } 
}

Solution 4 - Java

With Spring 4 it's possible to Self autowired

@Service
@Transactional
public class UserServiceImpl implements UserService{
    @Autowired
    private  UserRepository repository;

    @Autowired
    private UserService userService;
    
    @Override
    public void update(int id){
       repository.findOne(id).setName("ddd");
    }
     
    @Override
    public void save(Users user) {
        repository.save(user);
        userService.update(1);
    }
}

Solution 5 - Java

This is my solution for self invocation:

public class SBMWSBL {
    private SBMWSBL self;

    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void postContruct(){
        self = applicationContext.getBean(SBMWSBL.class);
    }
    
    // ...
}

Solution 6 - Java

You can autowired BeanFactory inside the same class and do a

getBean(YourClazz.class)

It will automatically proxify your class and take into account your @Transactional or other aop annotation.

Solution 7 - Java

Here is what I do for small projects with only marginal usage of method calls within the same class. In-code documentation is strongly advised, as it may look strange to colleagues. But it works with singletons, is easy to test, simple, quick to achieve and spares me the full blown AspectJ instrumentation. However, for more heavy usage I'd advice the AspectJ solution as described in Espens answer.

@Service
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
class PersonDao {

    private final PersonDao _personDao;

    @Autowired
    public PersonDao(PersonDao personDao) {
        _personDao = personDao;
    }

    @Transactional
    public void addUser(String username, String password) {
        // call database layer
    }

    public void addUsers(List<User> users) {
        for (User user : users) {
            _personDao.addUser(user.getUserName, user.getPassword);
        }
    }
}

Solution 8 - Java

The issue is related to how spring load classes and proxies. It will not work , untill you write your inner method / transaction in another class or go to other class and then again come to your class and then write the inner nested transcation method.

To summarize, spring proxies does not allow the scenarios which you are facing. you have to write the 2nd transaction method in other class

Solution 9 - Java

There is no point to use AspectJ or Other ways. Just using AOP is sufficient. So, we can add @Transactional to addUsers(List<User> users) to solve current issue.

public class UserService {
    
    private boolean addUser(String userName, String password) {
        try {
            // call DAO layer and adds to database.
        } catch (Throwable e) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();

        }
    }

    @Transactional
    public boolean addUsers(List<User> users) {
        for (User user : users) {
            addUser(user.getUserName, user.getPassword);
        }
    } 
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikeView Question on Stackoverflow
Solution 1 - JavaEspenView Answer on Stackoverflow
Solution 2 - JavaBunarroView Answer on Stackoverflow
Solution 3 - JavaKaiView Answer on Stackoverflow
Solution 4 - JavaAlmas AbdrazakView Answer on Stackoverflow
Solution 5 - JavaHlexView Answer on Stackoverflow
Solution 6 - JavaLionHView Answer on Stackoverflow
Solution 7 - JavaMario EisView Answer on Stackoverflow
Solution 8 - JavaUjjwal ChoudhariView Answer on Stackoverflow
Solution 9 - JavaJunyeong YuView Answer on Stackoverflow