Can someone explain the basic purpose of using Setter injections?
For instance variable injections we have
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,
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 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.