spring_boot_starter_cache

spring_boot_starter_cache adds caching to Spring for Dart applications, the Dart counterpart of Spring Boot's spring-boot-starter-cache. Put @Cacheable on a bean method, and repeated calls with the same arguments return the stored result instead of running the method again. It works on servers and in Flutter apps alike.

Why

Some methods are slow or costly and give the same answer for the same arguments: a network call, a database query, a heavy computation. Keeping their results by hand means a map per method, keys, invalidation and expiry, mixed into the business code. With this starter you annotate the method and the cache sits in front of it. Results live in memory by default, with an optional time to live and size limit. With spring.cache.type: disk they are kept on disk and outlive a restart, and you can put your own storage behind the same annotations.

Setup

# pubspec.yaml
dependencies:
  spring_boot_starter_cache: ^0.9.0

dev_dependencies:
  build_runner: ^2.17.0
  spring_core_dart_generator: ^0.9.0   # required: generates the proxies caching runs on

One import is enough: package:spring_boot_starter_cache/spring_boot_starter_cache.dart re-exports spring_boot_dart and spring_boot_starter_logging.

Example

import 'package:spring_boot_starter_cache/spring_boot_starter_cache.dart';

import 'spring_gen/main.spring.dart';

@Service()
class Books {
  Books(this.api);

  final CatalogApi api;

  // Slow: the API is called once per isbn, later calls read the cache.
  @Cacheable('books')
  Future<Book> find(String isbn) => api.load(isbn);

  // Callers asking for the same price at the same time share one request.
  @Cacheable('prices', sync: true)
  Future<double> price(String isbn) => api.price(isbn);

  // The book is gone: so is its cache entry.
  @CacheEvict('books', key: '#isbn')
  Future<void> delete(String isbn) => api.delete(isbn);
}

@SpringBootApplication()
void main(List<String> args) => runApplication(args);
# lib/resources/application.properties
spring.cache.simple.time-to-live=10m
spring.cache.simple.max-size=1000
spring.cache.simple.caches.prices.time-to-live=30s

What starts

Calls through the proxy only

The generator writes an AOP proxy for each bean (generator option aop_proxies, all by default), and the starter registers an advisor that wraps every method with a cache annotation. So, as in Spring:

@Service()
class Books implements BookService {
  Books(@Lazy() this._self); // the proxy of this same bean

  final BookService _self;

  @Cacheable('books')
  @override
  Book find(String isbn) => load(isbn);

  List<Book> findAll(List<String> isbns) =>
      [for (final isbn in isbns) _self.find(isbn)]; // cached; find(isbn) would not be
}

What is inside

In Spring (Java)

@EnableCaching
@SpringBootApplication
class ShopApplication {}

@Service
class Books {
  @Cacheable("books")
  public Book find(String isbn) { ... }
}

Differences that matter:

See also