Activating AOP
One of the things that confuses the use of annotations is that you often need to configure your framework to make it work properly.
See, for Spring to be able to intercept the call to the method to then demarcate a transaction, it uses a type of Aspect-Oriented Programming.
To activate this in Spring, you first need to set a TransactionManager
, for example:
<bean id="myTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
scope="singleton">
<property name="dataSource" ref="myDataSource" />
</bean>
Then 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 demarcating a transactional block with Spring is using the TransactionTemplate
.
In the documentation has a very simple example, where just inject the 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();
}
});
}
}
What have you tried so far? Any problem error? Consider including what you are trying.
– Bruno César