Skip to content

java_wrapping

klee0kai edited this page Dec 17, 2023 · 1 revision

Wrapping

What if your class doesn't want to hold objects. And every time take them from DI. This may be necessary for systems and programs that are most resistant to memory deficiencies. Each class uses the others only when necessary, otherwise releases them for purge opportunities.

The second need of the wrapping mechanism is lazy retrieval of objects. This approach allows you to gradually request new objects from DI and save yourself from the need to warm up features.

All this is available through the mechanism of wrapping the provided objects in shells - object providers.

The library allows you to wrap provided objects in the following wrappers

  • WeakReference - provides an object as a weak reference
  • SoftReference - provides an object as a soft reference
  • LazyProvide - provides an object through a lazy provider. When an object is used for the first time, the provider stores a link, the object is then held by the consumer.
  • PhantomProvide - provides a phantom provider. The object will not be held by the consumer, the object will be provided each time through DI, cached according to the rules in DI.

Wrapping can be customized for component methods.

@Component
public interface TechFactoryComponent {

    PhantomProvide<Battery> battery();

    LazyProvide<Ram> ramMemory();

}

And also use in injection.

public class GoodPhone {

    @Inject
    public PhantomProvide<Battery> battery;

    @Inject
    public LazyProvide<Ram> ram;

    public void create() {
        DI.inject(this);
    }

}

Creating your own wrappers

If you noticed a strange configuration of a component, then this is the place for you. Configuring the wrapperProviders component allows you to determine the available wrapping mechanisms in applications.

@Component(wrapperProviders = {CustomWrapper.class})

Each wrapperProviders must implement the ProviderWrapper interface to describe the mechanism for creating providers.

@WrappersCreator(wrappers = {CustomLazy.class})
public class CustomWrapper implements ProviderWrapper {

    @Override
    public <Wr, T> Wr wrap(Class<Wr> wrapperCl, Provider<T> originalProvider) {
        if (wrapperCl.equals(CustomLazy.class)) {
            return (Wr) new CustomLazy<T>(originalProvider::get);
        }
        return null;
    }

}

Clone this wiki locally