Producers
Producer<T> and the @Produces annotation — when DDI should call a factory instead of instantiating a class directly.
Work in progress. This page is the canonical reference for
Producer<T>and@Produces. Full content lands alongside the producer-vs-resolver tutorial (see the roadmap).
When you need a producer
Direct class instantiation works for the common case: DDI calls the no-arg
constructor, injects fields, runs @PostConstruct, done. You need a
producer when:
- The instance requires constructor arguments DDI can’t supply.
- The factory call has side effects you want explicit (opening a connection, reading config).
- The decision which subtype to instantiate is data-driven and you don’t want a
ClassResolverfor it.
The shape
package com.svenruppert.ddi.producer;
public interface Producer<T> {
T create();
}
Annotate the producer with @Produces to advertise it to the container:
@Produces
public class JdbcConnectionProducer implements Producer<Connection> {
public Connection create() {
return DriverManager.getConnection(System.getenv("DB_URL"));
}
}
Multiple producers per type
You can have many producers for the same impl. If you do, you must also declare
a ProducerResolver that picks between them — same rule as multiple impls
needing a ClassResolver.
See also
- Resolution rules — the full decision table for impls × producers × resolvers.
- ClassResolver — picks a class; producers wrap a factory.