Monday, November 23, 2009

OpenWebBeans and Java SE Project

Hi;

Today, we will learn how to easily use OpenWebBeans Container in a standalone mavenized Java Projects.

To use OpenWebBeans in a standalone project, just add the custom "openwebbeans.properties" file into your project classpath location that is "src/main/resources/META-INF/openwebbeans/" folder.

Content of the openwebbeans.properties file will be:

#Use Static HashMap
org.apache.webbeans.spi.JNDIService=org.apache.webbeans.spi.se.JNDIServiceStaticImpl

# Non Transactional
org.apache.webbeans.spi.TransactionService=org.apache.webbeans.spi.se.TransactionServiceNonJTA

#use the web metadata as default
org.apache.webbeans.spi.deployer.MetaDataDiscoveryService=org.apache.webbeans.spi.se.deployer.MetaDataDiscoveryStandard

#Lifecycle to start container
org.apache.webbeans.spi.Lifecycle=org.apache.webbeans.lifecycle.StandaloneLifeCycle

Add "beans.xml" file into your "src/main/resources/META-INF/beans.xml" as a marker file. That is it! Now, You can use dependency injection service from your standalone Java Projects .

For example:
public class Boot
{ 
 private static BeanManager beanManager;

public void start()
{
 //Boot container
 Lifecycle lifecycle = LifecycleFactory.getInstance().getLifecycle();         
 lifecycle.applicationEnded(null);    

 beanManager = lifecycle.getBeanManager();  
}

public void stop()
{
 //Stop container
 Lifecycle lifecycle = LifecycleFactory.getInstance().getLifecycle();         
 lifecycle.applicationStarted(null);      
}

public static void main(String args[])
{
  Boot boot = new Boot();
  boot.start();

  //USE YOUR BeanManager in your code for injections

 }
}

That is cool Hah :)

Cheers;

2 comments:

Jean-Louis said...

Awesome!
Thx for that.

vitamine d said...

OpenWebBeans core is the implementation of the core functionality of the specification that does not contain any Java EE dependent technology. It is used for implementing the general dependency injection framework.