Embedded Resin… with WebBeans!
One of the coolest new features of Resin 3.1.5 is embedding. Basically with a few simple lines of code, you can embed Resin into any existing Java application. More than that though, you can take advantage of Resin IoC/WebBeans even within the embedded environment. Let me give you an example…
Let’s start with simple embedding:
package demo;
import com.caucho.resin.*;
public class EmbeddedResin {
public static void main(String[] args)
throws Exception
{
ResinEmbed resin = new ResinEmbed();
HttpEmbed http = new HttpEmbed(8080);
resin.addPort(http);
resin.addWebApp(new WebAppEmbed("/", "ROOT"));
resin.start();
resin.join();
}
}
This basically starts up a new Resin within this application listening to port 8080 and serving up a webapp whose root is at “ROOT”. The resin.start() call starts the instance while the resin.join() waits for it to finish. Depending on the application, you may want to separate those calls.
So that’s very cool, but now what if I have a bean that I want to inject somewhere. Let’s say this FooBean:
package demo;
public class FooBean {
public String hello()
{
return "Hello from the world of Embedded Resin!";
}
}
I can actually do annotation based injection into a JSP for example:
<%@ page import="javax.webbeans.*,demo.*" %> <%! @In private FooBean _foo; %> <%= _foo.hello() %>
All I have to do is add a call to resin.addBean() to the example above:
package demo;
import com.caucho.resin.*;
public class EmbeddedIoC {
public static void main(String[] args)
throws Exception
{
ResinEmbed resin = new ResinEmbed();
HttpEmbed http = new HttpEmbed(8080);
resin.addPort(http);
resin.addBean(new BeanEmbed(new FooBean()));
resin.addWebApp(new WebAppEmbed("/", "ROOT"));
resin.start();
resin.join();
}
}
It’s pretty cool to me that you can drop a random bean into the embedded Resin, then just have it show up somewhere in a JSP.
I bundled this example up here. Just run “ant compile”, then “ant run” to use it.
