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
- No
@EnableCaching. Add the dependency and run the generator: the starter is found and switched on.spring.cache.type=noneturns caching off. - A
cacheManagerbean, anInMemoryCacheManager(aDiskCacheManagerwithspring.cache.type=disk), unless you declare aCacheManager(or a bean namedcacheResolver). - Annotations are checked when each bean is created, so a wrong combination (
keywithkeyGenerator,syncwithunless...) fails the startup, naming the member.
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:
- the cache applies to calls from other beans, which go through the proxy;
- a call through
thisinside the same class goes straight to the method and skips the cache. To call a cached method of your own class, inject the bean into itself with@Lazy():
@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
- Annotations:
@Cacheable,@CachePut,@CacheEvict,@Caching,@CacheConfig, keys and SpEL, async methods. - The in-memory caches: the default manager, time to live, size limits,
CacheManagerCustomizer. - Caches that outlive a restart:
spring.cache.type: disk,AsyncCache,CompositeCacheManager, memory in front of the disk withLayeredCacheManager, a file as a key. - Your own caches:
Cache,CacheManager, key generators, cache resolvers,CachingConfigurer, error handling. - Testing: switching caching off, checking caches, expiry with clocks.
- All properties: every key of the starter.
- Differences from Spring: what works differently than in Spring.
In Spring (Java)
@EnableCaching
@SpringBootApplication
class ShopApplication {}
@Service
class Books {
@Cacheable("books")
public Book find(String isbn) { ... }
}
Differences that matter:
- No
@EnableCaching. - Several cache names go to
@Cacheable.of(cacheNames: [...]). Futureresults are cached by value;Streamresults cannot be cached.- The in-memory caches have a time to live and a size limit, which Spring's
simpletype has not. - Caches on disk (
spring.cache.type: disk) andLayeredCacheManagerare this starter's own. - The full list is on Differences from Spring.