6/20/2006

5 Ways to Get Resources in EJB 3

1. Use resource injection with runtime info mapping.
For example,

package com.foo.ejb;
import javax.ejb.Remote;

@Remote public interface ResourceRemote {
public void hello();
}

package com.foo.ejb;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;

@Stateless
public class ResourceBean implements ResourceRemote {
@Resource(name="jdbc/employee")
private DataSource employeeDataSource;
You don't need ejb-jar.xml. For portable applications, you will need appserver-specific deployment plan to map the logical name (jdbc/employee) to the actual DataSource configured in the target runtime environment. For JavaEE SDK 5, Glassfish, and Sun Java System Application Server 9, it's sun-ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sun-ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 EJB 3.0//EN"
"http://www.sun.com/software/appserver/dtds/sun-ejb-jar_3_0-0.dtd">
<sun-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>ResourceBean</ejb-name>
<jndi-name>ResourceBean</jndi-name>
<resource-ref>
<res-ref-name>jdbc/employee</res-ref-name>
<jndi-name>jdbc/__default</jndi-name>
</resource-ref>
</ejb>
</enterprise-beans>
</sun-ejb-jar>

2. Non-portable applications don't even need this appserver-specific deployment plan; they can just use mappedName() field in @Resource:
@Stateless
public class ResourceBean implements ResourceRemote {
@Resource(name="jdbc/employee",
mappedName="jdbc/__default")
private DataSource employeeDataSource;
If application portability is not a big concern, you don't need any descriptor in this example. mappedName() field maps the logical name jdbc/employee to its counterpart (jdbc/__default) in the target runtime server environment. Be aware that application servers are not required by JavaEE platform to support mappedName() field. So it may cause trouble when you later try to migration your applications to another appserver. Glassfish, JavaEE SDK, and SJSAS 9 support mappedName().


3. Yet another option is to use default mapping rules in some application servers, without using runtime deployment plan. This is not portable either and some appservers may not have this functionality at all. In Glassfish, JavaEE SDK, and SJSAS 9, basically if resource logical name (without prefix) is the same as its physical name, then they are mapped together even without sun-ejb-jar.xml. For example,
@Stateless
public class ResourceBean implements ResourceRemote {
@Resource(name="jdbc/__default")
private DataSource defaultDataSource;
You don't need any descriptor, and it just works thanks to the default resource mapping.


4. Use EJBContext.lookup(String name), a new convenience method in EJB 3. The name parameter is relative to java:comp/env. For example,
package com.foo.ejb;
import java.sql.Connection;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.sql.DataSource;

@Stateless
public class ResourceBean implements ResourceRemote {
public void hello() {
DataSource
employeeDataSource =
(DataSource) sctx.lookup("jdbc/employee");
try {
Connection conn = employeeDataSource.getConnection();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
ejb-jar.xml is needed to declare this resource reference. Appserver-specific deployment plan is also needed for mapping, unless you use the default mapping mechanism above.
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
metadata-complete="false" version="3.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd">
<enterprise-beans>
<session>
<ejb-name>ResourceBean</ejb-name>
<resource-ref>
<res-ref-name>jdbc/employee</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
</resource-ref>
</session>
</enterprise-beans>
</ejb-jar>
sun-ejb-jar.xml is the same as in listing 1.

5. Use traditional JNDI lookup. This approach is basically the same as EJBContext.lookup(String name), except that JNDI lookup requires more lines of code, and uses an absolute reference name starting with java:comp/env or java:comp/
@Stateless
public class ResourceBean implements ResourceRemote {
@Resource private SessionContext sctx;

public void hello() {
DataSource ds = null;
try {
InitialContext ic = new InitialContext();
ds =
(DataSource) ic.lookup("java:comp/env/jdbc/employee");
} catch (NamingException ex){
throw new IllegalStateException(ex);
}
try {
Connection conn = ds.getConnection();
} catch(SQLException ex) {
throw new IllegalStateException(ex);
}
}
You need to declare this resource reference in ejb-jar.xml, and map it in sun-ejb-jar.xml, the same as in listing 4.

The biggest annoyance in JNDI lookup is that I have to try-catch javax.naming.NamingException, a checked exception. Since it's a low-level exception, it's not appropriate to just further throw it out. Probably for this reason, EJBContext.lookup(String name) just throws java.lang.IllegalArgumentException if name not found.

52 comments:

Rama said...

I am using the @Resource(name="examplebean") and I have added reference in the web.xml.
I am still having issues with calling my local session bean from a jsp page. I get the following error.
java.lang.ClassCastException: com.sun.enterprise.naming.SerialContext
Any thoughts?
Regards,
Ram

howto said...

Hi Ram,

If you want to inject EJB, use @EJB instead of @Resource. You cannot use @Resource to inject EJB references.

You cannot inject anything into JSP pages. You can inject EJB and/or resources into Servlet classes, Servlet listener classes, JSF beans.

You can inject examplebean into a servlet, and then look up this ejb reference in a jsp page that is in the same webapp as the servlet:

context.lookup("java:comp/env/examplebean");

ISHTEK said...

Thanks for this detail example code
on this topic, it's been a great help to me!!!!

Kamagra Jelly said...

yes,You cannot inject anything into JSP pages. You can inject EJB and/or resources into Generic Viagra,Kamagra,Lovegra Online Servlet classes, Servlet listener classes, JSF beans.

Anonymous said...

Your summarization is very much appreciated. Finding the same information by going over the Java EE specifications would not have been as easy

Ko Belko said...

I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks for sharing.
Friv
Friv 10000

tranbaongoc said...

I would like to say that this article really convinced me, you give me best information!
Y8
Friv 3

Bao An said...

you always bring everyone the most interesting and useful, I like it all, thank you.
Friv 4
Friv 5
Friv 100
Happy Wheels

Ha Nhi said...

This was a really great contest and hopefully I can attend the next one. It was alot of fun and I really enjoyed
Super smash flash 2|
Super mario bros|
Cooking games for girls

NGOCLAN said...

Do not know what to say, I liked your article and I hope you will have many entries or more.
Friv 14|
Kizi|
Friv4school

Friv online said...

when you see the stress in work, life, friv could well be a good site to try. thanks you for sharing friv games, friv online, friv.com, friv

Ha Thu Tran said...

Really impressive post. I enjoyed your article and planning to rewrite it on my own blog
Friv 1
Juegos Friv 3

Friv Games said...

Play free Friv games flash online games flash.
Thanks you for sharing
Friv Games | Friv Online

Love KidsTV said...

Thanks for your post. Click to play Plants vs Zombies , Solitaire,Tom And Jerry Games, Brain Games, Happy Wheels , Five Nights At Freddy's

Love KidsTV said...

Truyen ngon tinh hay la the loai truyen tinh cam
Truyen teen hay la nhung truyen tinh yeu tuoi teen
Don doc tai trang doc truyen online.

Anna said...

Great and Useful Article.

Online Java Course

Java Online Training

Java Course Online

J2EE training

online J2EE training

Best Recommended books for Spring framework

Java Interview Questions












Java Training Institutes in Chennai

Java Training in Chennai

J2EE Training in Chennai

java j2ee training institutes in chennai

hoang duong said...

I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks
Kizi 2
Friv 2

Kungfukangda said...

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
Friv 1000

Friv 10 said...

Thanks you for sharing !
Friv 10
Kizi 10
Yepi 2

XUKA said...

You need to kill time, you need entertainment. Refer to our website. hope you get the most comfort.
Friv 234

Friv5 said...

You need to kill time, you need entertainment. Refer to our website. hope you get the most comfort.
Thanks for sharing !
Friv 5
Kizi 1
Yepi 3

tranduyphong said...

after hours of work tired, you need entertainment. Refer to our website. hope you get the most comfortable
Kizi 1000

Ka Sa said...

I Discovered Many new things from your article. Thank you for this!
Friv Game
Friv

Dash Geometry said...

Love your blog!! Why don't you blog anymore :( I miss your blog. Wahhh
fireboy and watergirl
Geometry Dash

Alice Denny said...

This is the story that I never read about Roy Gilchrist. Thanks for sharing interesting information about him
Earn To Die | Big Farm | Slitherio
Tank Trouble | Happy Wheels
Goodgame Eepire | Slither.io

Pham Dinh said...

You want to relax after a stressful working hours. Refer to our website. Hope you get the most comfort.
Thanks for sharing !Y8 arcade

Tdt 3535 said...

You'd have time to look these kids active. Please visit our website and let us play the game interesting. Thanks for sharing !
Happy Wheels | Five Nights at Freddy’s | Friv.com | Kizi 4

angelina jolie said...

Good job. All of them are Useful! ..
Y8Y8Y8

Unknown said...

Thanks for the share loved reading the article, please do share more like this wiht us .
Cookie Clicker
Cookie Clicker play
Cookie Clicker game
Cookie Clicker online

Friv game said...

Kizi 100 le ofrece sólo lo mejor te escojan juegos en línea gratis. Play all the top rated friv4school, friv flash games today.

trump Ivanka said...

Every day just relaxing a bit to increase the work efficiency of you. Take a look at our website

Friv 4 School
Friv 1
GirlsGoGames

Melinda Gates said...

You want to relax after a stressful working hours. Refer to our website. Hope you get the most comfort.
Thanks for sharing !

Friv Games
Y2
Friv 200

Craft Mine said...

Great information, I will tweet to my friends to get them to check it out. keep it up. Thanks for sharing!.If have a long time than visit to:
minecraft | facebook baixar | whatsapp baixar | baixar facebook | photo grid

Linda Rose said...

great article, I was very impressed about it, wish you would have stayed next share
happy wheels

Malia Obama said...

Thanks a lot! It is definitely an terrific internet site!
Friv 2
Friv 4
Friv 3

a10friv said...

you'd have time to look these kids active. Please visit our website and let us play the game interesting.
A10 Friv
Friv 10
Y6

windows movie maker said...

Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone!
slither io

geometry dash said...

Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone! I believe a lot of people will be surprised to read this article!
bloons tower defense 5

Friv 2016 said...

Code is good.

Yepi said...

Code is good.

Y8
Kizi

happy wheels said...

Thank you for sharing them! I hope you will continue to have similar posts to share with everyone!
abcya

usps tracking said...

it's so simple yet beautiful! I believe evryone will thank us for your post!
bloxorz

Linda Rose said...

Thank you for such a sweet tutorial - all this time later, I've found it and love the end result. I appreciate the time you spent sharing your skills.
Papa Louie 2

Run 3 | Stick Run 2
unblocked games | Potty Racers 3

Vũ Diệu Linh said...

today is a beautiful day, do you want to participate in games? It will help your become more comfortable, i feel very great, please visit my website, to feel.
Friv 4

Unknown said...

Here you can find all free FRIV 2000 games, choice the game you like and play right now.
Friv 2000

Friv 2 said...

We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work.

Friv2
Friv7
Friv8
Friv9
Friv20
Friv100
Friv100
Friv10000

Unknown said...

I love all the posts, I really enjoyed,would like more information about this, because it is very nice, Thanks for sharing.
ABCya
ABCya
ABCya 3
ABCya 4
ABCya 5

tinh linh said...

Thank you very much for your post, So kind for you, I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear. Friv 5000 Games is abbreviation for free flash games. Our friv games are 100% safe to play, thank you.
Friv 5000

Vũ Diệu Linh said...

Thank you very much for the information you shared, it's all I've been looking for. Today is a beautiful day, do you want to participate in games? It will help your become more comfortable, i feel very great, please visit my website, to feel.
Friv 4

Trái Xoan said...

Thanks for sharing this quality information with us. I really enjoyed reading your article. I found this as an informative and interesting post, so i think it is very useful and knowledgeable. Today is a great day, please visit my website, to feel.
friv fun

Bella Swan said...

Thank you for giving posts and articles were very amazing. I really liked as a part of the article. With a nice and interesting topics. Thanks for posting.
I like play games Y8

Renesmee Foy said...

I don't know what to say, I liked your article and I hope you will have many entries or more, thanks for taking the time to show us.
Friv Unblocked
Y8 Unblocked
Kizi Unblocked