JavaConfig provides full support for the annotation-driven declarative
transaction management features provided by the core Spring Framework
with the @AnnotationDrivenTx
annotation:
public class FooServiceImpl implements FooService { @Transactional public void doStuff() { // invoke multiple calls to data access layer } }
@Configuration @AnnotationDrivenTx public class Config { @Bean public FooService fooService() { return new FooServiceImpl(fooRepository()); } @Bean public FooRepository fooRepository() { return new JdbcFooRepository(dataSource()); } @Bean public PlatformTransactionManager transactionManager() { return new DataSourceTransactionManeger(dataSource()); } @Bean public DataSource dataSource() { // create and return a new JDBC DataSource ... } }
public class Main { public static void main(String[] args) { JavaConfigApplicationContext ctx = new JavaConfigApplicationContext(Config.class); // The FooService retrieved from the container will be proxied for tx management FooService fooService = ctx.getBean(FooService.class); // call the @Transactional method on the proxy - transactional behavior is guaranteed fooService.doStuff(); } }
Like Spring XML's <tx:annotation-driven>
element,
@AnnotationDrivenTx
expects the presence of a bean named
transactionManager
of type PlatformTransactionManager
as in the example above. Should you wish to forego this convention and name
a transaction manager bean another name, you may do as follows:
@Configuration @AnnotationDrivenTx(transactionManager="txManager") // specify explicitly the bean to use public class Config { @Bean public PlatformTransactionManager txManager() { return new DataSourceTransactionManeger(dataSource()); } // other beans... }
The other attributes available to the @AnnotationDrivenTx
are similar
to the attributes to the <tx:annotation-driven>
element. See
the
related documentation and the JavaDoc for @AnnotationDrivenTx
for details.