Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using Setter Injections

 
vinodreddy kisanagaram
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Dumitru Postoronca
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Dumitru.

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic