Replacing Factories

Jakob Jenkov
Last update: 2016-05-20

Replacing Factories

From version 2.1.9 it is possible to replace factories at runtime. When replacing a factory all factories referencing the old factory will instead reference the new factory. However, if any factory in the container, or component in your application, holds references to cached instances from the old factory (singletons, flyweights etc.), these references will not be updated to reference cached instances from the new factory.

Here is how to replace a factory in the container:

IContainer           container     = new Container();
ScriptFactoryBuilder scriptBuilder = new ScriptFactoryBuilder(container);

//adding a factory
scriptBuilder.addFactory("test = * com.jenkov.MyProduct(); ");

//replacing the factory
scriptBuilder.replaceFactory("test = * com.jenkov.MyProduct('Replacement');" );

//replacing the factory with a Java factory.
//  MyNewFactory must be a Java factory class.
//  See "Getting Started" for more details on Java factories.
JavaFactoryBuilder javaBuilder = new JavaFactoryBuilder(container);
javaBuilder.replaceFactory("test", new MyNewFactory());

It is also possible to replace several script factories at a time, by using the ScriptFactoryBuilder.replaceFactories(InputStream) method. All factories in the new script will replace existing factories.

Replacing a factory that does not exist (no factory added by that name) is equivalent to adding the factory.

Jakob Jenkov

Featured Videos

Java ConcurrentMap + ConcurrentHashMap

Java Generics

Java ForkJoinPool

P2P Networks Introduction

















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next