Search code examples
javadependency-injectioncdiweld

Initialize Java CDI Without Weld?


If I understand it correctly, Java CDI should be independent of Weld. But all examples I see use Weld to initialize the container.

I am trying to use CDI without Weld because while I'd like to use DI, I'm very limited on memory.

Here is an example of my LoggerFactory-

@ApplicationScoped
public class LoggerFactory {

    @Produces
    @Singleton
    public Logger getLogger() {
        return LogManager.getLogger("com.myapp");
    }

}

And my trying to fetch it in Main-

Logger logger = CDI.current().select(Logger.class).get();

When I do this I get Unable to locate CDIProvider.

Is it possible to use CDI without additional libraries? How can I get my Logger in this instance?


Solution

  • CDI is a Java EE specification. It specifies how things should be done but itself provides not functionality.

    Weld is the reference implementation of the CDI spec. An alternative implementation of the CDI is for example Apache OpenWebBeans. Either of these implementations will be able to give you the features of CDI.

    Weld provides an extension which will boot a CDI bean manager in Java SE: https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#weld-se

    But be careful because due to my experience Weld SE consumes a lot of memory and needs some time to scan the class-path for (bigger) SE-Applications.