Core Java

Bootstrap CDI 2.0 in Java SE

Abstract

This is a quick reference for bootstrapping CDI 2.0 in a Java SE application.

CDI 2.0 (JSR 365)

Maven Dependency

<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-core</artifactId>
    <version>3.0.2.Final</version>
</dependency>

beans.xml

File location is /META-INF/beans.xml. This file is optional, though I’ve found it’s still good to have.

<beans version="2.0" 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
     http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd" 
    bean-discovery-mode="all"
>
    <scan>
        <exclude name="org.jboss.weld.**" />
    </scan>  
</beans>

Java SE Application

package org.ferris.cdi.example.main;

import javax.enterprise.inject.se.SeContainer;
import javax.enterprise.inject.se.SeContainerInitializer;

/**
 * The main() method for this application
 *
 * @author <a href="mailto:mjremijan@yahoo.com">Mike Remijan</a>
 */
public class Main {
    public static void main(String[] args) {

        SeContainer container
            = SeContainerInitializer.newInstance().initialize();

        Main main
            = container.select(Main.class).get();

        //. . .
    }
}

Summary

That’s it…enjoy!

Published on Java Code Geeks with permission by Michael Remijan, partner at our JCG program. See the original article here: Bootstrap CDI 2.0 in Java SE

Opinions expressed by Java Code Geeks contributors are their own.

Michael Remijan

Michael Remijan is a System Architect at the Federal Reserve Bank St. Louis. He is co-author of 'EJB 3 In Action Second', an active blogger in the Java EE community, a Java EE Guardian, and JavaOne presenter. He has developed enterprise systems for B2C and B2B commerce, manufacturing, astronomy, agriculture, telecommunications, national defense, healthcare, and financial areas.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
ruu
ruu
3 years ago

This code throws “WELD-001334: Unsatisfied dependencies for type Main with qualifiers”.

What needs to be changed to get this running?

Back to top button