Enabling AOP
One of the things you confuse in using annotations is that you often need to configure your framework for them to function properly.
See, for Spring to be able to intercept the method call to then demarcate a transaction, it uses an Aspect Oriented Programming type.
To enable this in Spring, you first need to define a TransactionManager
, for example:
<bean id="myTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
scope="singleton">
<property name="dataSource" ref="myDataSource" />
</bean>
Next, set the setting to enable AOP in Spring:
<tx:annotation-driven transaction-manager="myTransactionManager" />
If you use Spring Boot or configuration via classes, just put the equivalent settings in your configuration class. See documentation here .
TransactionTemplate
Annotation is not the only way to use transactions. The programmatic version of marking a transactional block with Spring is using TransactionTemplate
.
In the documentation has an example very simple, where you just need to inject TransactionManager
and instantiate the transaction object:
public class SimpleService implements Service {
// single TransactionTemplate shared amongst all methods in this instance
private final TransactionTemplate transactionTemplate;
// use constructor-injection to supply the PlatformTransactionManager
public SimpleService(PlatformTransactionManager transactionManager) {
Assert.notNull(transactionManager, "The ''transactionManager'' argument must not be null.");
this.transactionTemplate = new TransactionTemplate(transactionManager);
}
public Object someServiceMethod() {
return transactionTemplate.execute(new TransactionCallback() {
// the code in this method executes in a transactional context
public Object doInTransaction(TransactionStatus status) {
updateOperation1();
return resultOfUpdateOperation2();
}
});
}
}