I know you said you didn't want to have to get it from the context xml, but I can't see an easy and non-fragile way around it.
In Spring 2.0 and greater you can use the <util:property-path />
element to reference a property of another bean. Let's say your DataSource
is declared like so (note: I'm going to use the p-namespace
throughout for brevity):
<bean id="dataSource" class="com.example.SimpleDataSource"
p:user="db_user"
p:password="letmein"
p:driverClass="com.example.CabDriver"
p:jdbcUrl="jdbc:example:@localhost:1729:magicdb" />
I'm assuming that your JdbcTemplate
is being used by some data access object. Let's say it looks like this:
public class SimpleDao implements ExampleDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
So the Spring config to construct this DAO is like so:
<bean id="dao" class="com.example.SimpleDao"
p:dataSource-ref="dataSource" />
Now to our problem: how to get the JdbcUrl
property into our DAO? Let's add a setter:
public class SimpleDao implements ExampleDao {
private String jdbcUrl;
// ...
public void setJdbcUrl(String jdbcUrl) {
this.jdbcUrl = jdbcUrl;
}
// ...
And finally we inject this using the aforementioned <util:property-path />
element:
<bean id="dao" class="com.example.SimpleDao"
p:dataSource-ref="dataSource">
<property name="jdbcUrl>
<util:property-path path="dataSource.jdbcUrl" />
</property>
</bean>
The URL is available from the bean named dataSource
using getJdbcUrl
(note that this is on the concrete DataSource, not the interface), so the property-path element tells Spring to get the value from there and use it as the value for the DAO's property.
This isn't too much code (it's one setter and one extra property) and you're guaranteed to always have the same value injected into both beans.