A FactoryBean creates a container product; accurate object-type and singleton declarations let Spring wire that product predictably.
Spring FactoryBean: expose the product type without constructing it
Two objects share one registration
The container name receiptSigner normally resolves to the ReceiptSigner product. Prefixing the name with an ampersand retrieves its ReceiptSignerFactoryBean. This distinction matters when diagnostics inspect the factory while application code injects the signer. FactoryBean is an extension point for special construction; a normal @Bean method is easier when creation has no unusual type or lifecycle requirements. Registration choices] should stay explicit.
Tell the container what it will receive
getObjectType should return ReceiptSigner.class before the product is constructed. A null or incorrect type can make type-based lookup and autowiring miss the signer. isSingleton must agree with getObject: returning true while manufacturing a fresh mutable signer on each call creates a false lifecycle promise. The example holds one signer and returns it consistently. If the signer owns a socket or key handle, close it through an explicit lifecycle contract; destruction rules] are separate from product lookup.
Verify type lookup and identity
Refresh a context, inject ReceiptSigner by type, then request the named product twice and assert identity when the factory says singleton. Retrieve the factory by its prefixed name and assert its getObjectType. A factory-level unit test alone cannot show whether the container cached the product or selected it for injection. Watch startup cost if construction contacts a remote signing service.
Implementation contract
final class ReceiptSignerFactoryBean
implements FactoryBean<ReceiptSigner> {
private final ReceiptSigner signer;
ReceiptSignerFactoryBean(SigningKeyHandle handle) {
this.signer = new ReceiptSigner(handle);
}
@Override public ReceiptSigner getObject() { return signer; }
@Override public Class<?> getObjectType() {
return ReceiptSigner.class;
}
@Override public boolean isSingleton() { return true; }
}Cost and verification
Accurate type prediction avoids constructing a product just to answer a lookup. A singleton signer saves repeated initialization but concentrates concurrent use and cleanup in one object; its implementation must be thread-safe.
Common Mistakes
- Do not return null from getObjectType when the product type is known.
- Do not claim singleton while returning different stateful products.
- Do not confuse the FactoryBean object with the product injected under its registration name.
Read next
Spring @Component versus @Bean: choose who constructs the dependency, Spring bean scopes: singleton identity is not thread safety, Spring lifecycle cleanup: close container-owned resources, Spring BeanPostProcessor: instance callbacks and the early-bean trap, Spring constructor injection: required dependencies stay visible.
