Embedded resources
By default the generator copies every file of your package's lib/resources/ into the generated module, as Dart string constants. At run time the module registers them, and resources: locations (resources:application.yml, resources:templates/mail.txt) read them from memory. This works the same in dart run, AOT executables, Flutter and the web, with no asset declarations.
Why
In Spring, src/main/resources/ ends up on the classpath, inside the jar, and classpath: locations read it from there. A Dart program has no classpath:
- an AOT executable is a single file, and the project folder is usually not next to it;
- a Flutter app on a phone has no project folder at all, and reads files only through declared assets;
- a web app has no file system.
Embedding the files at build time makes them part of the program on every platform. application.properties, message bundles, templates and small data files are found wherever the program runs, without flutter: assets: entries in pubspec.yaml and without code that differs per platform.
What the generator writes
For this folder:
lib/resources/
application.properties
banner.txt
covers/default.png
data/books.json
the module gets a resources: argument (excerpt from the server guide of the repository, texts shortened):
_i1.BeanModule get $application => _i1.BeanModule(
r'application',
[/* ... */],
resources: const {
r'application.properties': _i1.EmbeddedResource.text(
'# NEON Books server: the configuration every profile shares.\n...',
),
r'banner.txt': _i1.EmbeddedResource.text(
' _ _ ___ ___ _ _ ___ _\n...',
),
r'covers/default.png': _i1.EmbeddedResource.base64(
r'iVBORw0KGgoAAAANSUhEUgAAAHgAAAC0CAIAAADQLH9KAAABCUlEQVR42u3QQQ0A...',
),
r'data/books.json': _i1.EmbeddedResource.text(
'[\n {"isbn": "9780441013593", "title": "Dune", ...}\n]\n',
),
},
);
The rules:
- Every file below
lib/resources/, at any depth, except.dartfiles. The key is the path belowlib/resources/, with/separators. - Sorted by path, so the output is the same on every machine.
- Text or base64. A file whose bytes are valid UTF-8 becomes
EmbeddedResource.text; any other file becomesEmbeddedResource.base64. A text file in another encoding (an ISO-8859-1.propertiesfile) is therefore embedded as base64, and the config reader decodes it when an import names its encoding. - At most 1 MB per file. A file larger than 1,048,576 bytes is skipped, with a build warning:
lib/resources/static/main.dart.js is larger than 1048576 bytes and is not embedded;
ship it as a Flutter asset or a file instead.
The limit exists because embedded files are compiled into the program: each one makes the executable, the app or the JavaScript bundle bigger, and loads with it. Large files belong elsewhere: a Flutter asset (asset: locations), a file next to the executable (file: locations), or a download. A Flutter web build served by spring_boot_starter_web, for example, is read from a folder with spring.web.resources.static-locations: file:..., because main.dart.js and canvaskit.wasm are larger than the limit.
Which modules embed them
Every generated module embeds its package's lib/resources/:
- the
@SpringBootApplicationoutput,$application; - every
@ComponentScanmodule, including those of a library or a starter. A library's own files (its default configuration, its templates) travel with its module to every application that uses it.
When a package has both, both modules carry the same files. That costs nothing at run time: a path is registered once.
At run time
A module registers its files when it is created, before any config file is read:
- The first registration of a path wins, as the first classpath entry does in Java. A file registered later under the same path is ignored.
- Hot reload. The files are registered under the module's name, so a module created again after a hot reload replaces its own earlier files, and a changed
application.propertiesis seen. - Directories on disk come first.
spring_boot_starter_testaddstest/resources/, which is searched before the embedded files, so a test config file wins over the packaged one. - A path that is not embedded (a file you added without running
build_runner) is read fromlib/resources/<path>relative to the working directory, where there is one. resources:cannot climb out. A location with..abovelib/resources/(resources:../../secret) finds nothing.
See Resources for the Resource API and the location prefixes.
Applications outside lib/
An application whose main is not in lib/ (in bin/, test/ or example/) gets more than one resources folder. The generator embeds, lowest precedence first:
- the package's
lib/resources/; - then
<dir>/lib/resources/for each directory from the top down to the directory ofmain.
For main in example/shop/bin/main.dart:
lib/resources/ lowest precedence
example/lib/resources/
example/shop/lib/resources/
example/shop/bin/lib/resources/ highest precedence
The nearer a folder is to main, the higher its precedence. When two folders have a file with the same path, the nearer file replaces the other one completely; the files are not merged. So an example's example/lib/resources/application.properties wins over the package's lib/resources/application.properties, as an application's configuration wins over a library's. Files that exist in only one folder are all embedded.
Folders that do not exist are skipped. For main in lib/, only lib/resources/ is read.
@ComponentScan modules always embed only lib/resources/.
build-info.properties for actuator apps
Spring Boot's build plugins write META-INF/build-info.properties, which the actuator's info endpoint shows. The generator does the same for an application with the actuator. When:
- the package is an application (
publish_to: noneinpubspec.yaml), - its
dependencieslistspring_boot_actuatororspring_boot_starter_actuator, - and none of its resources folders has a
build-info.propertiesof its own,
the @SpringBootApplication output embeds a build-info.properties made from pubspec.yaml:
build.artifact=neon_books_server
build.name=neon_books_server
build.version=1.4.0
build.version is left out when pubspec.yaml has no version. There is no build time, on purpose: the generated file would change on every build, and so would the fingerprint used by hot reload. If you want a time or other values, write lib/resources/build-info.properties yourself; the generator then embeds yours as it is.
The example of a published package gets none, since it would change with every release. The actuator reads the file from spring.info.build.location (resources:build-info.properties by default).
Choosing how files reach the app
Each file of lib/resources/ reaches a Flutter web app one of four ways, chosen by two properties; the code that reads it (resources:content/...) is the same in all of them.
| Way | Configuration | First load | Opening another page |
|---|---|---|---|
| In the binary (default) | nothing | Downloads every file with the app | Nothing to download |
| One by one | spring.resources.embed.exclude: [content/**], the folders under flutter: assets: |
Only the app | Downloads that page's file |
| Together, after the app shows | the above, and spring.resources.prefetch.locations: ['content/**/*.md'] |
Only the app; the page shown, then one file with all the others a second after the splash | Nothing to download, once that file is in |
| Together, behind the splash | the above, and spring.resources.prefetch.stage: tasks |
The app and the file with all of them, before it shows | Nothing to download |
They mix: exclude and prefetch.locations are globs, so some files can stay in the binary (the configuration always does), some come one by one (pictures), some together (the pages). The search has its own file, the index the build writes (spring.search.prebuilt), on or off on its own.
The files left out stay Flutter assets even when they come together: the page opened first is read from its own file before the packed one arrives, a file that failed to come together still comes on its own, and the app knows which files exist from the start.
Leaving files out of the binary
Embedding is instant and works everywhere, but it puts every byte in the program. A site with hundreds of Markdown pages or many pictures carries all of them, though a visitor reads a few. spring.resources.embed.exclude lists globs below lib/resources/ that the build does not embed:
# lib/resources/application.yml
spring:
resources:
embed:
exclude: [content/**, images/**]
# pubspec.yaml
flutter:
assets:
- lib/resources/content/
- lib/resources/content/docs/
- lib/resources/images/
- The files left out are Flutter assets now. The locations stay the same:
resources:content/docs/beans.mdis found in the app's assets when it is not embedded. In a mobile or desktop app the files are inside the package; on the web a file is downloaded only when it is read. - A Flutter asset directory includes only its own files, not those of its subdirectories. List every directory that has a file left out. The build prints the exact lines to add when one is missing:
spring.resources.embed.exclude leaves 2 directories out of the binary that are no
Flutter assets, so resources: finds nothing there at run time. Add to pubspec.yaml,
under flutter: assets: ...
- lib/resources/content/
- lib/resources/content/docs/
- The configuration is always embedded, whatever the globs say:
application*.yml,application*.properties, any.propertiesfile and everything inconfig/. The start reads it at once. - A list or one text of comma-separated globs both work (
spring.resources.embed.exclude=content/**,images/**). The build reads the key from the configuration files oflib/resources/. - The 1 MB limit applies to the files that are embedded only.
- A file that is embedded and also under
flutter: assets:is read from the binary: the app never downloads it on its own. It is only copied intobuild/web/assets/for nothing, so leave out ofpubspec.yamlwhat you do not exclude.
Synchronous reads (readAsStringSync) work for embedded files only. A file read as an asset has no bytes at hand, so use readAsString and readAsBytes.
| Embedded (the default) | Left out (assets) |
|---|---|
| small files read at the start: templates, small data | many or big files read on demand: documentation pages, pictures |
| instant, synchronous or asynchronous reads | asynchronous reads; on the web one download per file |
| the binary carries them | the binary stays small |
Numbers from this documentation site, with content/** left out (834 Markdown files):
| All embedded | Left out | |
|---|---|---|
main.dart.wasm |
11.6 MB | 3.7 MB (about 1 MB compressed) |
| JavaScript fallback | 14.5 MB | 4.2 MB |
| Opening a page | carries all 834 files | downloads the 2 Markdown files of the page |
The search reads only the files of the language searched; see Documents.
A file can also be put anywhere under flutter: assets:, not only in lib/resources/, and read as asset:path. It has the same features: patterns, relative links, pages for search engines. See Assets and fonts.
Downloading them together
Files left out of the binary are downloaded one by one, when each is read. On a site that is a wait on every page the visitor opens. spring.resources.prefetch puts them in one file the app downloads once, after it is shown:
spring:
resources:
embed:
exclude: [content/**]
prefetch:
locations: ['content/**/*.md'] # what goes in the file
stage: app # app (default) or tasks
delay: 1s # after the app is shown
# pubspec.yaml
flutter:
assets:
- lib/resources/spring_gen/prefetch/
- The build writes
lib/resources/spring_gen/prefetch/resources.json, a line per piece, never embedded. It warns whenpubspec.yamldoes not list the directory. stage: app: the download startsdelayafter the splash is gone, so the first page and its pictures come first, and PageSpeed does not count it. A page opened before the file is there is downloaded on its own, as without it.stage: tasks: the splash waits for it, so every page is there from the first tap; on a slow network the splash is longer.- The files are kept in memory as resources, read a piece at a time, so the app keeps drawing.
resources:finds them at once. - On the web only; an app on a device reads its assets from the device.
- Text files only. On this site the file holds every page in both languages: 1.2 MB with brotli, one request.
Pages for search engines from assets
The spring_flutter_seo builder makes pages for Markdown folders (see Pages for search engines). It reads the folders of asset: as well as those of resources:: the Markdown files of the Flutter assets of pubspec.yaml (a directory entry gives its own files). A route or spring.flutter.web.seo.content[n].location with asset:docs/ makes the same pages as resources:content/docs/. Files left out of the binary make pages too.
Tips
- Run
build_runnerafter you change a file oflib/resources/. During development a file missing from the generated module is read from disk, but an AOT executable or a Flutter app only has what was embedded. - Keep secrets out of
lib/resources/. Embedded files are in the compiled program, and anyone with the program can read them. Use placeholders such as${SUPPLIER_API_KEY:}and set the value from the environment. - Generated code holds the files as string literals. A large text file makes the generated
.spring.dartfile large too, which editors handle less well.
In Spring (Java)
// src/main/resources/templates/mail.txt, inside the jar
Resource resource = new ClassPathResource("templates/mail.txt");
lib/resources/ plays the role of src/main/resources/, and resources: the role of classpath:. The differences: files are embedded at build time into the generated module instead of packed into a jar, files above 1 MB are left out, and a change needs a new build_runner run.