First of all, EJBs are part of Java EE, so you cannot use them in Java SE. However, CDI can be used in the Java SE environment, my example will show you how to use it with Weld, but there are other implementations - note that CDI is just a specification, and Weld is one of the implementations of this specification.
To use Weld, you need to either put weld-se-xxx-Final.jar in the classpath, or specify its dependency in Maven as
<dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se</artifactId> <version></version> </dependency>
Then you need to run the container in the main method, so do something like this
public static void main(String[] args) throws IOException { Weld weld = new Weld(); WeldContainer container = weld.initialize(); Application application = container.instance().select(Application.class).get(); application.run(); weld.shutdown(); }
This should get you started, then you can use CDI Producers to inject your EntityManager
@Produces @RequestScoped public EntityManager createEntityManager() { return Persistence.createEntityManagerFactory("mgr").createEntityManager(); } public void closeEM(@Disposes EntityManager manager) { manager.close(); }
See Also Provides documentation on using CDI in Java SE .
Petr mensik
source share