blogger templates blogger widgets
This is part of a list of blog posts.
To browse the contents go to

Bind and lookup beans using resource-env-ref (tomcat)

We will try to bind and lookup a custom bean using resource-env-ref configuration.

Let's write our beans first.

package sample.bean;

public class MyBean {

 private String foo = "Default Foo";
 private int bar = 0;

 public String getFoo() {
  return (;
 public void setFoo(String foo) { = foo;
 public int getBar() {
  return (;
 public void setBar(int bar) { = bar;
 public String toString() {
  return "MyBean [foo=" + foo + ", bar=" + bar + "]";

Declare in your web application's web.xml:

<description>Object factory for MyBean instances</description>

Note the convention used here for ref names.
bean/[a factory name for bean] (bean/MyBeanFactory) rather than bean/[bean name] (bean/MyBean).

Like I mentioned before, you need to specify the resource factory to be used, since containers make the resource available before the application starts.
Tomcat provides resource factories for common usages.
For bean creation we used, org.apache.naming.factory.BeanFactory.

Add the below entry in the tomcat's context.xml found under [tomcat_installation]/conf/context.xml.

<resource name="bean/MyBeanFactory" auth="Container" type="sample.bean.MyBean" factory="org.apache.naming.factory.BeanFactory"  bar="23"/>
If you had given the option to use workspace metadata while adding the server to eclipse. To check double click the server, which opens its configuration screen.

If this is the case then you need to modify context.xml available under Servers Folder inside your workspace.

And here goes our servlet code,

try {
 Context initCxt =  new InitialContext();
 // one could use relative names into the sub-context
 Context envContext = (Context) initCxt.lookup("java:comp/env");
 MyBean myBean2 = (MyBean)envContext.lookup("bean/MyBeanFactory");
 // or we could do it in a single line
 // MyBean myBean =  (MyBean)initCxt.lookup("java:comp/env/bean/MyBeanFactory");
 // System.out.println(myBean.toString());
} catch (NamingException e) {

MyBean [foo=Default Foo, bar=23]

Continue reading: Bind and lookup beans using resource-env-ref and custom factory class (tomcat)

No comments:

Post a Comment