Posts Tagged ‘Spring Framework’

Bean.

Inheritance Demo, In the example given below we are going to tell about the inheritance in the Spring framework. By inheritance we mean a way of forming new classes using classes that have already been defined. Here we have created a simple bean and used this bean as a template for creating other beans.

parent” class=”mybean” >:-Creates a  Parent bean which would be used as a template for creating other beans. Here “mybean” is the name of the bean class which would be referred in the xml file with the id “parent“.

mybean” parent=”parent”>:-Creates a child bean which would be inheriting from the parent bean defined above.

parent=”parent”:-Specify that this bean is inheriting the properties of some other bean. 

  <property name=”name” value=”Roseindia.net”/>
</bean>
mybean” parent=”parent”>
</bean>

context.xml

<?xml version="1.0" encoding="UTF-8"?>
xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean id=“parent” class=“mybean” >
  <property name=“name” value=“Roseindia.net”/>
  </bean>  <bean id=“child” class=“mybean” parent=“parent”>
  <property name=“address” value=“Rohini”/>
  </bean>

  <bean id=“subchild” class=“mybean” parent=“parent”/>

</beans>

Main.java

This is the file through which we are retrieving the property of the bean defined above. Some of the methods which are used here are as follows:-

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(“context.xml”)):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document

new ClassPathResource(“context.xml”):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.

(bf.getBean(“child”)):-This method returns an instance of the bean named “child”, which is shared or independent, of the given bean name.

(bf.getBean(“subchild”)):-This method returns an instance of the bean named “subchild, which is shared or independent, of the given bean name.

stringBuilder.append(“Bean”):-This is the method of the class string Builder which appends the specified string to this character sequence.

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
public class Main {
  public static void main(String[] args) throws Exception {
  XmlBeanFactory bf = new XmlBeanFactory(new ClassPathResource("context.xml"));
  System.out.println("===============Inheritance demo=================");
  System.out.println(bf.getBean("child"));
  System.out.println(bf.getBean("subchild"));
 }
}
class mybean {
  private String name;
  private String address;
  public void setName(String name) {
  this.name = name;
  }
  public void setAddress(String address) {
  this.address = address;
  }
  @Override
  public String toString() {
  final StringBuilder stringBuilder = new StringBuilder();
  stringBuilder.append("Bean");
  stringBuilder.append("{name='").append(name).append('\'');
  stringBuilder.append(", address=").append(address);
  stringBuilder.append('}');
  return stringBuilder.toString();
  }
}

Output of the program

Nov 25, 2008 3:39:29 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [context.xml] ===============Inheritance demo================= Bean{name=’Roseindia.net’, address=Rohini} Bean{name=’Roseindia.net’, address=null} BUILD SUCCESSFUL (total time: 1 second)

Download source code

Advertisements

Building a datasource for a web of data

JDBC Template Batch update example, In the tutorial we have discussed about  batchUpdate()  method of class JdbcTemplate in Spring framework. The Batch update methods are used to executes multiple SQL updates query on a single JDBC Statement. The example given below consists of the code to delete and update data of the table Simultaneously.

context.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:util="http://www.springframework.org/schema/util"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/util 
       http://www.springframework.org/schema/util/spring-util-2.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
       http://www.springframework.org/schema/lang 
       http://www.springframework.org/schema/lang/spring-lang-2.0.xsd">
          <bean id="dataSource" 
                                 destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://192.168.10.75:3306/komal"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>
       <bean id="lobHandler">
        <property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>
    </bean>
        <bean id="nativeJdbcExtractor" 
   />
       <bean id="jdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

Main.java

ApplicationContext ac = new ClassPathXmlApplicationContext(“context.xml”, Main.class):-ApplicationContext is the interface that is used to  provide Bean factory methods for accessing application components. Here we Creates an instance of this interface to access context.xml and Main.java.

DataSource source = (DataSource) ac.getBean(“dataSource”):-Data source is an Interface which provides a way for connecting to the physical data source. Here we created datasource for making connection to our xml document in which we have declared the bean.

jt.batchUpdate(new String[]{“update employee set departement = ‘Finance#'”, “delete from employee where EmployeeId =31” }):-With the use of this method we are executing two SQLquery simultaneously. This method executes multiple Sql updates on a single JDBC statement.

import javax.sql.DataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
class Main {
    public static void main(String args[]) {
        try {
            ApplicationContext ac = new
                    ClassPathXmlApplicationContext("context.xml", Main.class);
            DataSource source = (DataSource) ac.getBean("dataSource");
            JdbcTemplate jt = new JdbcTemplate(source);
            jt.batchUpdate(new String[]{"update employee set departement = 'Finance#'",
                        "delete from employee where EmployeeId =31"
                    });
            System.out.println("Data updated successfully");
        } catch (Exception e) {
            e.printStackTrace();
                    }
    }
}

Output of the program

Data updated successfully
BUILD SUCCESSFUL (total time: 2 seconds)
  Table before updation    Table after updation

Download source code

Western bean cutworm damage to dry bean

XML Bean-Injection, The given example below gives the brief description of the extension name spaces that can be used in the spring framework With the use of extensible name space you can  make Spring configuration file more simpler to use for many tasks which can occurs repeatedly . Extension namespaces also allows us to supply property values by using attributes .

xmlns:p=”http://www.springframework.org/schema/p&#8221;:-Here we have introduced  namespace:“p” that cannot be validated.

<bean id=”mybean”  class=”Inject”>:- Here “Inject” is the name of the bean class which would be referred in the xml file with the id “mybean“.

p:name=”Girish” :-Here we simply use the property name in the “p” namespace, as in “p:name”.

context.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.xsd">
<bean id="mybean"
class="Inject"
p:name="Girish"
p:age="24"
p:address="Noida"
p:company="Roseindia.net"
p:email="girish@roseindia.net"/>
</beans>

Main.java

This is the file through which we are retrieving the property of the bean defined above. Some of the methods which are used here are as follows:-

XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource(“context.xml”)):-This method creates an instance of the XmlBeanFactory which is used to read bean definition from an XML document

new ClassPathResource(“context.xml”):-Creates a new ClassPathResource for ClassLoader .Here the context.xml is the file which is to be loaded.

String.format(“Name: %s\n” +”Age: %d\n” ):-This method formats an object to produce a string. Here

%s:-is for accessing String value.

%d:-is for accessing Integer value.

import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; public class Main {   public static void main(String[] args) {   XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(   "context.xml"));   Inject demo = (Inject) beanFactory.getBean("mybean");   System.out.println(demo);   } } class Inject {   private String name;   private int age;   private String company;   private String email;   private String address;  public void setAddress(String address) {   this.address = address;   }   public void setCompany(String company) {   this.company = company;   }  public void setEmail(String email) {   this.email = email;   }   public void setAge(int age) {   this.age = age;   }   public void setName(String name) {   this.name = name;   }   @Override   public String toString() {   return String.format("Name: %s\n" +   "Age: %d\n" +   "Address: %s\n" +   "Company: %s\n" +   "E-mail: %s",   this.name, this.age, this.address, this.company, this.email);   } }

Output of the Spring Injection Example program

Nov 25, 2008 1:03:13 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [context.xml]
Name: Girish
Age: 24
Address: Noida
Company: Roseindia.net
E-mail: girish@roseindia.net
BUILD SUCCESSFUL (total time: 1 second)

Download source code

Java (programming language)

In this section we will learn about Spring cglib library and understand the importance of it. You will also find the url to download cglib library

What is cglib?

The cglib is high performance library in Java. It is used to extend Java classes and implement interfaces in runtime. It is one the best quality code generation library available in Java. The latest version of cglib library can be downloaded from http://cglib.sourceforge.net/.

The cglib library is free software and can be used for personal and commercial purposes.

Spring 3 framework uses cglib2 for manipulating the Java classes in runtime. The cglib library is not included in Spring 3.0 distribution. So, you have to manually download and include in your project.

On the cglib home page you will find the link to download.

If you don’t include the cglib dependency in your Spring 3 project you might get the following error:

Jan 2, 2010 3:22:07 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh

INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@15eb0a9:
startup date [Sat Jan 02 15:22:07 IST 2010]; root of context hierarchy

Exception in thread “main” java.lang.IllegalStateException: CGLIB is required to process @Configuration classes.
Either add CGLIB to the classpath or remove the following @Configuration bean definitions: [spring3HelloWorldConfig]

at org.springframework.context.annotation.ConfigurationClassPost
Processor.enhanceConfigurationClasses(
ConfigurationClassPostProcessor.java:257)

at org.springframework.context.annotation.ConfigurationClass
PostProcessor.postProcessBeanFactory(
ConfigurationClassPostProcessor.java:147)

at org.springframework.context.support.AbstractApplicationContext.invokeBean
FactoryPostProcessors(
AbstractApplicationContext.java:624)

at org.springframework.context.support.AbstractApplicationContext.invoke
BeanFactoryPostProcessors(
AbstractApplicationContext.java:614)

at org.springframework.context.support.AbstractApplication
Context.refresh(
AbstractApplicationContext.java:398)

at org.springframework.context.annotation.Annotation
ConfigApplicationContext.<init>(
AnnotationConfigApplicationContext.java:65)

at net.roseindia.Spring3HelloWorldConfigTest.main(Spring3HelloWorldConfigTest.java:9)