Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You cannot access <code>dataSource</code> in the constructor. Spring first instantiates the bean (using the default constructor in your case) and then wires the properties.</p> <p>There are <a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/beans.html#beans-factory-lifecycle-initializingbean" rel="nofollow">a number of ways</a> to deal with that.</p> <p><strong>Constructor injection</strong></p> <pre><code>&lt;bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest"&gt; &lt;constructor-arg ref="dataSource"/&gt; &lt;/bean&gt; </code></pre> <p>And class</p> <pre><code>public class JdbcTest { private DataSource dataSource; public JdbcTest(DataSource dataSource) throws SQLException { this.dataSource = dataSource; conn = dataSource.getConnection(); stmt = conn.createStatement(); } } </code></pre> <p><strong>InitializingBean</strong></p> <pre><code>public class JdbcTest implements InitializingBean { private DataSource dataSource; // setter for dataSource public void afterPropertiesSet() { // run the actual test onn = dataSource.getConnection(); stmt = conn.createStatement(); } } </code></pre> <p><strong>Init method</strong></p> <pre><code>&lt;bean id="jdbcTest" class="org.springdemo.jdbc.JdbcTest" init-method="runTest"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;/bean&gt; </code></pre> <p>And class</p> <pre><code>public class JdbcTest { private DataSource dataSource; // setter for dataSource public void runTest() { // run the actual test } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload