Documentation versions (currently viewingVaadin 24)

Modifying How Dependencies Are Loaded with DependencyFilter

Using the DependencyFilter interface to control which dependencies are loaded.

You can use the @JavaScript, @CssImport, and @StyleSheet annotations or an imperative API to add resources (or dependencies) to your application when needed. But sometimes, finer control is needed. For example, when bundling resources into multiple bundles, you may want to make the application import the right bundle when some specific resource is requested.

To control how the dependencies are loaded, and which files are effectively added to, or removed from, the loading process, you can use the DependencyFilter interface.

Here is one example. It removes all dependencies and adds one single bundle when running in production mode:

public class BundleFilter implements DependencyFilter {
    public List<Dependency> filter(List<Dependency> dependencies,
            VaadinService service) {

        if (service.getDeploymentConfiguration().isProductionMode()) {
            dependencies.add(new Dependency(Dependency.Type.STYLESHEET,
                        "my-style.css", LoadMode.EAGER));

        return dependencies;
You can also use the context:// and base:// protocols on dependencies returned by the DependencyFilter. These protocols are resolved after the filters are applied. The context:// protocol is resolved to the servlet context root and the base:// protocol is resolved to the base URI of the loaded page.

The DependencyFilter objects are called in two particular situations: when a LitTemplate is parsed for the first time, and when a set of dependencies are about to be sent to the client.

  • When a route changes and a new set of components are requested, all dependencies are gathered in a list and sent to the filters for evaluation. The filters can change, remove or add new dependencies, as needed.

DependencyFilter objects allow you to change, add and remove any dependencies. You may leave your application in a broken state if you remove a required dependency for your project without providing a suitable replacement. With great power comes great responsibility.

With your DependencyFilter in place, you need to add it to a ServiceInitEvent, which is sent when a Vaadin service is initialized. Take a look at the ServiceInitListener tutorial for how to configure it.