top of page
Screenshot 2024-02-07 at 10.10.49.png


Automatic code conversion of a DIY component factory to EJB dependency injection

Key Takeaways

Asset 2_4x.png

Older Java back-end code often contains static object factories that are made widely available to the codebase

Asset 3_4x.png

Converting object factories to EJB dependency injection typically causes various rippling effects through the class hierarchy and implementations.

Asset 4_4x.png

Large-scale automatic conversion of static object factories to dependency injection is possible, given JFocus static code analytics in combination with OpenRewrite.

The factory pattern

Older Java back-end code may still contain the following pattern: a number of singletons are lazily instantiated, and made broadly available to the codebase using a static “factory class”:


This pattern can be used to offer a central static point of access that provides and manages functional (mostly singleton) components. In the example code the singletons are the implementations of IWork and ISleep; the Factory class (2) is accessible anywhere, and provides access to these singleton instances. The class InstantiatedByContainer (1) using the singletons is managed by the back-end technology in use (3).


From Factory to EJB container

One of the aspects of modernizing older enterprise applications is to transfer object provision and policy to the EJB container as much as possible. EJB containers provide a better way of implementing this pattern, one where, amongst a host of other benefits, there is no code dependency on the implementations.

In this document we discuss the different aspects of an automatic approach of converting the factory-style approach to EJB managed instances with annotated fields, along with the secondary effects that occur during such a transition. In case of instances that are directly managed by the EJB container, the factory-provided instances can be replaced with injected fields by the @Inject annotation:


or, alternatively, using injection via the constructor:


If the factory is accessed in classes that are not managed by the EJB container, the annotation approach cannot be used. Take the example of a helper class that is constructed in a class instantiated by the container, and the factory is accessed in that helper class. The required singleton can be passed on to the helper class, either via its constructors, or, maybe repeatedly via method calls into the helper class:


can either be converted to passing the fields to the constructor:


or, when we’d rather not change the constructors, to passing the fields in every call to the Helper’s methods:


Leave your email to receive the full paper

Download link will be sent to this email address

Thanks! Check your email for the download link.

bottom of page