How to inject java.util.Properties into a spring bean



Que: -How to inject java.util.Properties into a spring bean?

Properties object is similar to Map based collection, only difference is keys also strings and values also strings. In case of Map based collection key can be any object and value also can be any object.

To inject Properties into a spring bean following steps are involved: –

Step 1: –Make java.util.Properties type variable as dependency in the spring bean.

Step 2:-To indicate the spring container to create the Properties object make use of <props> tag.

Step 3: –To specify each element of the Properties object make use of <props> tag.

e.g.: –

<bean name=”h” class=”com.nit.spring.HelloBean”>
 <property name=”properties”>
     <prop key=”name”> Rama < /prop>
        <prop key=”address”> Hyderabad < /prop>
   < /props>
 < /property>
< /bean>

Note: –value of the key attribute becomes the key of the properties of Properties object. The content of <prop> tag become value of the property of Properties object.

Que: -Develop an enterprise application in which, all three layers are implemented?

Data Access Layer: –

  1. (float getBalance (int accno))
  • AccountDAO class has “javax.sql.DataSource” as dependency.
  • DataSouurce (interface) object provides database connection to the AccountDAO class.
  • DataSource is alternative to DriverManager to providing database connections to java applications.

In a spring application DataSource is used following the given steps: –

Step 1: –Make java.sql.DataSource variable as dependency and write appropriate constructor or setter method for spring container to implement setter injection or constructor injection.

For example: –

public class AccountDAO
     private DataSource datasource;
     public void setDataSource (DataSource datasource)

Step 2: –configure the implementation class DataSource interface as spring bean in configuration file.

e.g.: –

<bean id=”dataSource”
       <property name=”driverClassName”
          value=”oracle.jdbc.driver.OracleDriver” />
       <property name=”url”
          value=”jdbc:oracle:thin:@localhost:1521:server” />
       <property name=”username” value=”scott” />
       <property name=”password” value=”tiger” />
< /bean>

To make use of BasicDataSource as dependency in a spring application we need to place two jar files in classpath.

  1. commons-dbcp.jar
  2. commons-pool.jar

Note: –As we are using Oracle-Driver we need to place classes12.jar also in classpath.

Step 3: –In DAO methods get the database connection using “datasource”.

e.g.: –

public class AccountDAO
     DataSource datasource;
     Public float getBalance (int accno) throws
AccountNotFoundException, DataAccessException
           Connection con=datasource.getConnetion ();


Leave a Reply

Your email address will not be published. Required fields are marked *