
# 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

```yaml
# 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

```dart
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);
```

```properties
# 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=none` turns caching off.
- **A `cacheManager` bean**, an `InMemoryCacheManager` (a `DiskCacheManager` with `spring.cache.type=disk`), unless you declare a `CacheManager` (or a bean named `cacheResolver`).
- **Annotations are checked when each bean is created**, so a wrong combination (`key` with `keyGenerator`, `sync` with `unless`...) 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 `this` inside 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()`:

```dart
@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](annotations.md): `@Cacheable`, `@CachePut`, `@CacheEvict`, `@Caching`, `@CacheConfig`, keys and SpEL, async methods.
- [The in-memory caches](in-memory-caches.md): the default manager, time to live, size limits, `CacheManagerCustomizer`.
- [Caches that outlive a restart](disk-caches.md): `spring.cache.type: disk`, `AsyncCache`, `CompositeCacheManager`, memory in front of the disk with `LayeredCacheManager`, a file as a key.
- [Your own caches](custom-caches.md): `Cache`, `CacheManager`, key generators, cache resolvers, `CachingConfigurer`, error handling.
- [Testing](testing.md): switching caching off, checking caches, expiry with clocks.
- [All properties](properties.md): every key of the starter.
- [Differences from Spring](differences.md): what works differently than in Spring.

## In Spring (Java)

```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: [...])`.
- `Future` results are cached by value; `Stream` results cannot be cached.
- The in-memory caches have a time to live and a size limit, which Spring's `simple` type has not.
- Caches on disk (`spring.cache.type: disk`) and `LayeredCacheManager` are this starter's own.
- The full list is on [Differences from Spring](differences.md).

## See also

- [AOP proxies](../spring-core-dart/aop/proxies.md)
- [SpEL](../spring-core-dart/spel/index.md)
- [@Lazy](../spring-core-dart/beans/lazy.md)
- [What a build contains](optimizations.md)
