Sunday, November 5, 2017

CDI in Java SE 8

In Eclipse (pueah, I know, IntelliJ is much better) create a simple Java project, give it the Maven feature, and create this structure:


Add this dependency:

<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-shaded</artifactId>
<version>3.0.0.Final</version>
</dependency>


and the code to bootstrap the WELD engine is:

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

public class MyMain {
 public static void main(String[] args) {
  SeContainer container = SeContainerInitializer.newInstance().initialize();
  CDITester cdiTester = container.select(CDITester.class).get();
  cdiTester.greet();
 }
}



or also (thanks gist-it)



The beans.xml file is empty and required, without it you would get this error:


Exception in thread "main" java.lang.IllegalStateException: WELD-ENV-000016: Missing beans.xml file in META-INF
at org.jboss.weld.environment.se.Weld.initialize(Weld.java:742)
at org.jboss.weld.environment.se.Weld.initialize(Weld.java:174)
at org.pierre.cditests.MyMain.main(MyMain.java:8)




The whole solution is here https://github.com/vernetto/JavaMonAmour/tree/master/pvcdi.
When you start the MyMain inside Eclipse (no need to deploy it Wildfly!!!) you should see:


Nov 05, 2017 5:13:17 PM org.jboss.weld.bootstrap.WeldStartup
INFO: WELD-000900: 3.0.0 (Final)
Nov 05, 2017 5:13:17 PM org.jboss.weld.bootstrap.WeldStartup startContainer
INFO: WELD-000101: Transactional services not available. Injection of @Inject UserTransaction not available. Transactional observers will be invoked synchronously.
Nov 05, 2017 5:13:17 PM org.jboss.weld.environment.se.WeldContainer fireContainerInitializedEvent
INFO: WELD-ENV-002003: Weld SE container aabfa8d7-3cf1-44da-8b63-173e651f18a8 initialized
Hello, pierre.
Weld SE container aabfa8d7-3cf1-44da-8b63-173e651f18a8 shut down by shutdown hook


I really wonder why Java still in 2017 doesn't offer you an ready-made CDI engine in SE.... in fact, I wonder why we still have this separation between SE and EE.... nonsense.... it will go away, like all the nonsense...


Incidentally , https://dzone.com/articles/how-to-inject-property-file-properties-with-cdi really simple way to inject property values with annotations (Spring has a similar concept




No comments: