Using SeContainerInitializer
it will load an instance by ServiceLoader.load(...)
and initialize it.
public static SeContainerInitializer newInstance() {
return findSeContainerInitializer();
}
private static SeContainerInitializer findSeContainerInitializer() {
SeContainerInitializer result;
Iterator<SeContainerInitializer> iterator = ServiceLoader.load(SeContainerInitializer.class, SeContainerInitializer.class.getClassLoader()).iterator();
if (!iterator.hasNext()) {
throw new IllegalStateException("No valid CDI implementation found");
}
try {
result = iterator.next();
} catch (ServiceConfigurationError e) {
throw new IllegalStateException("Error while instantiating SeContainerInitializer", e);
}
if (iterator.hasNext())
throw new IllegalStateException("Two or more CDI implementations found, only one is supported");
return result;
}
Weld is one implementation of SeContainerInitializer
so if it exists on the classpath SeContainerInitializer.newInstance()
method will create a new Weld
instance and call initialize()
method on this object.
Some hints which is a good choice
SeContainerInitializer.newInstance()
is a factory method. If you want to create a vendor-independent application it would be good. But Weld is the reference implementation of CDI specification. Honestly I don't think choosing another implementation is necessary.
new Weld().initialize()
will create a WeldContainer
(which is an implementation of SeContainer
). Using this method you will get a vendor-lock but you can use a lot of useful extra features (e.g. add alternatives or interceptors programmatically).
My opinion is: In this case vendor-lock doesn't matter anithing.
Conclusion
If you're planning to change CDI implementation anything else than Weld use independent SeContainerInitializer.newInstance()
otherwise just create a Weld
instance.
If I were you I would use new Weld()
way.