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 (this.foo);
 }
 public void setFoo(String foo) {
  this.foo = foo;
 }
 public int getBar() {
  return (this.bar);
 }
 public void setBar(int bar) {
  this.bar = bar;
 }
 @Override
 public String toString() {
  return "MyBean [foo=" + foo + ", bar=" + bar + "]";
 }
}


Declare in your web application's web.xml:


<resource-env-ref>
<description>Object factory for MyBean instances</description>
<resource-env-ref-name>bean/MyBeanFactory</resource-env-ref-name>
<resource-env-ref-type>sample.bean.MyBean</resource-env-ref-type>
</resource-env-ref>

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());
 System.out.println(myBean2.toString());
} catch (NamingException e) {
 e.printStackTrace();
}      
}


Output:
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