JdbcTemplate - 记录dataSource连接URL

时间:2010-05-28 06:12:51

标签: java spring logging jdbc datasource

有没有办法在Java中记录JdbcTemplate的DataSource连接URL?

该字段存在于DataSource中,但没有getter可以访问它。当然我可以从应用程序上下文xml中读取DataSource属性,但我想以其他方式执行。

3 个答案:

答案 0 :(得分:2)

我知道你说你不想从上下文xml中获取它,但是我看不到一种容易且不易碎的方式。

在Spring 2.0及更高版本中,您可以使用<util:property-path /> element来引用另一个bean的属性。假设你的DataSource被宣布为这样(注意:为简洁起见,我将全面使用p-namespace):

<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" />

我假设某个数据访问对象正在使用您的JdbcTemplate。让我们说它看起来像这样:

public class SimpleDao implements ExampleDao {
    private JdbcTemplate jdbcTemplate;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }
}

所以构造这个DAO的Spring配置是这样的:

<bean id="dao" class="com.example.SimpleDao"
    p:dataSource-ref="dataSource" />

现在我们的问题:如何将JdbcUrl属性纳入我们的DAO?让我们添加一个二传手:

public class SimpleDao implements ExampleDao {
    private String jdbcUrl;
    // ...
    public void setJdbcUrl(String jdbcUrl) {
        this.jdbcUrl = jdbcUrl;
    }
    // ...

最后我们使用前面提到的<util:property-path />元素注入了它:

<bean id="dao" class="com.example.SimpleDao"
    p:dataSource-ref="dataSource">
    <property name="jdbcUrl>
        <util:property-path path="dataSource.jdbcUrl" />
    </property>
</bean>

使用dataSource从名为getJdbcUrl的bean中获取URL(请注意,这是在具体的DataSource上,而不是接口上),因此property-path元素告诉Spring从中获取值在那里,并将其用作DAO财产的价值。

这不是太多的代码(它是一个setter和一个额外的属性),并且保证始终将相同的值注入到两个bean中。

答案 1 :(得分:1)

如果该字段存在,您会考虑使用反射来访问它吗?这种方法可能不是面向未来的,但可能足以满足您的需求。

答案 2 :(得分:0)

以下是我从Tomcat容器中获取并注入NamedParameterJdbcTemplate的JNDI数据源所做的工作。

String datasourceUrl = null;
try { // Log which database we are connected to.
    JdbcTemplate jdbcTemplate = (JdbcTemplate)onyxReportingNamedParameterJdbcTemplate.getJdbcOperations(); // Get underlying JdbcTemplate
    datasourceUrl = jdbcTemplate.getDataSource().getConnection().getMetaData().getURL();
} catch (SQLException e) { // No biggie, don't exit, this was just for info.
    log.error("Non-fatal error: unable to get datasource for logging which database we are connected to.", e);
}
log.info("Datasource URL: " + datasourceUrl);

应用程序上下文:

<jee:jndi-lookup id="onyxReportingDS" jndi-name="jdbc/OnyxReadTLCDS" expected-type="javax.sql.DataSource" />
<bean id="onyxReportingNamedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="onyxReportingDS" />
</bean>