wood burning stoves 2.0*
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes Using Setter Injections Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "Using Setter Injections" Watch "Using Setter Injections" New topic
Author

Using Setter Injections

vinodreddy kisanagaram
Greenhorn

Joined: Jan 08, 2008
Posts: 9
Hi,


Can someone explain the basic purpose of using Setter injections?

For instance variable injections we have
@Resource
private javax.sql.Datasource dataSource
Here the container makes a JNDI look up for dataSource and injects the same into the bean

For setter injections,
@Resource(name="jdbc/actionBazaarDB")
on public void setDataSource(DataSource dataSource)

In seter injections, the underlying purpose is to set the dataSource externally. So when the dataSource is getting set externally, what is the use of having the annotation Resource on top of this setter method?

Does the usage of @Resource mean that if the dataSource is not set externally, container by default injects a resource by looking up the JNDI?

***<br />K Vinod Reddy
Dumitru Postoronca
Ranch Hand

Joined: May 06, 2008
Posts: 46
In both cases the container will set the datasource. The (minor) advantage of setter injection is that you might want to use/test this class out of container, so you will call the setters/inject the dependencies yourself.
vinodreddy kisanagaram
Greenhorn

Joined: Jan 08, 2008
Posts: 9
Thanks Dumitru.

Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

Dumitru Postoronca wrote:In both cases the container will set the datasource. The (minor) advantage of setter injection is that you might want to use/test this class out of container, so you will call the setters/inject the dependencies yourself.

Actually, it's not minor at all It's quite useful to do unit test.


[My Blog]
All roads lead to JavaRanch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using Setter Injections