Friday, July 12, 2013

Spring Core JDBC example for beginners.

Hi friends in this example I am going to describe Spring Basic JDBC example with Spring2.5. No more complexity here.
Here is my project packaging stucture.




               
            Here I have configured org.apache.commons.dbcp.BasicDataSource in my spring bean configuration file, this BasicDataSource belongs to apache. This is depends on driverClassName, connection url, userName and password to create the connection between java and Oracle DB.

Here is my applicationContext.xml spring bean configuration file. Here you may need to change the values as per your environment.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

       <bean id="basicDataSource" class="org.apache.commons.dbcp.BasicDataSource">
              <property name="driverClassName">
                     <value>oracle.jdbc.driver.OracleDriver</value>
              </property>
              <property name="url">
                     <value>jdbc:oracle:thin:@localhost:1521:XE</value>
              </property>
              <property name="username">
                     <value>lovababu</value>
              </property>
              <property name="password">
                     <value>********</value>
              </property>
       </bean>
</beans>

SpringJDBCTest.java

             Here is may SpringJDBCTest.java class, nothing is new here, if you are already familiar with traditional JDBC.  I have already configured my basicDataSource through spring configuration file, so spring container take care of my datasource creation I no need to worry about datasource creation here. 

Simple I am getting the connection from the basicDataSource and creating statement and loading the STUDENT data from table.
         Here is the Sql Script to create table and insert records.

CREATE TABLE STUDENT1
(
  STD_NO NUMBER NOT NULL
, STD_NAME VARCHAR2(20 BYTE) NOT NULL
, AGE NUMBER NOT NULL
, CONSTRAINT STUDENT_PK1 PRIMARY KEY (STD_NO) ENABlE
);
INSERT INTO STUDENT VALUES(1213 , 'somename' , 8);

package com.lova.springjdbc.test;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


/**
 * @author Lovababu
 *
 */
public class SpringJDBCTest
{
       private static ApplicationContext context = null;
       static
       {
              context = new ClassPathXmlApplicationContext("applicationContext.xml");
       }
       public static void main(String[] args)
       {
              DataSource dataSource = (DataSource) context.getBean("basicDataSource");
             
              try
              {
                     Connection connection = dataSource.getConnection();
                     Statement statement = connection.createStatement();
                     ResultSet rs = statement.executeQuery("SELECT * FROM STUDENT");
                     while(rs.next())
                     {
                           System.out.println("Row "+ rs.getRow());
                           System.out.println("    Student NO:"+rs.getInt(1) + " Name:"+rs.getString(2)+ " Age:"+rs.getInt(3));
                     }
                    
              } catch (SQLException e) {
                     e.printStackTrace();
              }
       }

}

Jar Required: Spring 2.5 version I used for this example.
  • spring-beans.jar
  • spring-context.jar
  •  spring-core.jar
  • commons-attributes-api.jar
  • commons-attributes-compiler.jar
  •  commons-logging.jar  log4j-1.2.14.jar
  •  ojdbc14.jar
  •  org.apache.commons.dbcp.jar
  • org.apache.commons.pool.jar


Thank YOU, please leave your comment  J

Tuesday, July 2, 2013

How to use factory-method in Spring framework.

Hello in this post we are going to discuss about factory-method attribute in spring bean configuration and how to use factory-method in bean configuration.

Actually spring has implemented many design patterns like singleton, factory, prototype, Decorator etc. still if you want to use your own factory method design pattern with own implementation you can use factory-method attribute in your bean configuration to get the Objects from factory class.

You can also read my previous posts below.
               

             Here is my packaging structure.


In this example I am using FactoryClass.java as my factory. In this class I have defined two static methods each one will return different objects, getFacultyDS() method returns the FacultyDS object and getStudentDS() method returns StudentDS object.

Here is my Spring bean configuration file. Let’s have a look at my bean configurations. Here I have register my FactoryUtilizer class with the id “factoryUtilizer”, this utilizes the factory-method attribute in its configuration file to get the objects from the FactoryClass.

<property name="studentDS">
 <bean factory-method="getStudentDS" class="com.lova.spring.fm.FactoryClass" />
</property>

      What the above tag does here, I believe you are familiar with setter injection. Here as soon as the container read this configuration it invokes the factory method which we have configured as factory-method attribute on FactoryClass and it takes the returned object and injects into target objects through setter injection.

Note: Here factory method should be static on your factory class.

applicationConfiguration.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      
       <bean id="factoryUtilizer" class="com.lova.spring.fm.FactoryUtilizer">
              <property name="studentDS">
                     <bean factory-method="getStudentDS" class="com.lova.spring.fm.FactoryClass" />
              </property>
              <property name="facultyDS">
                     <bean factory-method="getFacultyDS" class="com.lova.spring.fm.FactoryClass" />
              </property>
       </bean>
      
</beans>

FactoryClass.java:

                Here is my FactoryClass.java; it is some thing looks like singleton with two Static methods.

package com.lova.spring.fm;

/**
 * @author Lovababu
 *
 */
public class FactoryClass
{

       private static StudentDS studentDS = null;

       private static FacultyDS facultyDS = null;

       private FactoryClass()
       {
       }

       public static StudentDS getStudentDS()
       {
              if (studentDS == null)
              {
                     studentDS = new StudentDS();
              }
              return studentDS;
       }

       public static FacultyDS getFacultyDS()
       {
              if (facultyDS == null)
              {
                     facultyDS = new FacultyDS();
              }
              return facultyDS;
       }

}

FacultyDS.java:

                Simple Java class having single method sayHello()

package com.lova.spring.fm;

/**
 * @author Lovababu
 *
 */
public class FacultyDS
{

       public void sayHello()
       {
              System.out.println("I am in FacultyDS.sayHello()");
       }
}


StudenDS.java:

package com.lova.spring.fm;

/**
 * @author Lovababu
 *
 */
public class StudentDS
{
       public void sayHello()
       {
              System.out.println("I am in StudentDS.sayHello()");
       }
}

FactoryUtilizer.java

                In this class I am injecting the both StudentDS and FacultyDS objects using setter injection. Check my configuration file.

package com.lova.spring.fm;

/**
 * @author Lovababu
 *
 */
public class FactoryUtilizer
{

       private StudentDS studentDS;
      
       private FacultyDS facultyDS;

       public StudentDS getStudentDS()
       {
              return studentDS;
       }

       public void setStudentDS(StudentDS studentDS)
       {
              this.studentDS = studentDS;
       }

       public FacultyDS getFacultyDS()
       {
              return facultyDS;
       }

       public void setFacultyDS(FacultyDS facultyDS)
       {
              this.facultyDS = facultyDS;
       }
}

FactoryMethodTest.java

                Here is my Test class, loading the ApplicationContext and getting the bean FactoryUtilizer from container and accessing FacultyDS and StudentDS object using getter methods then invoking the method on those classes.

package com.lova.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lova.spring.fm.FactoryUtilizer;

/**
 * @author Lovababu
 *
 */
public class  FactoryMethodTest
{

                public static void main(String[] args)
                {
                                ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
                               
                                FactoryUtilizer factoryUtilizer = (FactoryUtilizer) context.getBean("factoryUtilizer");
                               
                                factoryUtilizer.getFacultyDS().sayHello();
                               
                                factoryUtilizer.getStudentDS().sayHello();

                }

}

RequiredLibraries:

Ø      org.springframework.core-3.0.5.RELEASE.jar
Ø      org.springframework.context-3.0.5.RELEASE.jar
Ø      org.springframework.beans-3.0.5.RELEASE.jar
Ø      org.springframework.asm-3.0.5.RELEASE.jar
Ø      org.apache.log4j-1.2.15.jar
Ø      org.apache.commons.logging-1.1.1.jar
Ø      org.springframework.expression-3.0.5.RELEASE.jar


Thank you, and try to execute this application by copying from this blog. Please leave you comment here. J

UA-41474183-1