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

previous-button-hisubmit-hi

 

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”>
   <props>
     <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. AccountDAOInterface.java (float getBalance (int accno))
  2. AccountDAO.java
  3. AccountNotFoundException.java
  4. DataAccessException.java
  • 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)
   {
       this.datasource=datasource;
   }
   ---------------------------
}

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

e.g.: –

<bean id=”dataSource”
   Class=”org.apache.commons.dbcp.BasicDataSource”>
       <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 ();
           -----------------------
           -----------------------
     }
}

previous-button-hisubmit-hi

Share Button

Map based collection example and Properties example

previous-button-hisubmit-hi

Que: -Map based collection example.

  1. Student.java
  2. College.java
  3. bean.xml
  4. ExecuteBean.java
package com.nit.spring;

public class Student
{
   private int rollno;
   private String name;
   public void setRollno (int rollno)
   {
       this.rollno=rollno;
   }
   public int getRollno ()
   {
       return rollno;
   }
   public void setName (String name)
   {
         this.name=name;
   }
     public String getName ()
     {
           return name;
     }
       public void displayStudentDetails ()
    {
         System.out.println (“Rollno:”+ rollno);
         System.out.println (“Name:”+ name);
    }
}

————————————————————

package com.nit.spring;
import java.util.Map;

public class College
{
     private Map <Integer, Student> students;
     public void setStudents (Map<Integer, Student> students)  //HashMap object is created
     {
         this.students=students;
     }
     public Map <Integer, Student> getStudents ()
   {
         return students;
   }
}

————————————————————

bean.xml

<beans>
 <bean name=”c” class “com.nit.spring.College”>
  <property name=”students”>
   <map> //knowing that HashMap object have to be create
    <entry key-“1001”>
     <bean id=”s1” class=”com.nit.spring.Student”>
      <property name=”rollno” value=”1001”/>
       <property name=”name” value=”Rama” /> 
< /bean>
< /entry>
   <entry key-“1002”>
    <bean id=”s2” class=”com.nit.spring.Student”>
     <property name=”rollno” value=”1002” />
      <property name=”name” value=”Rahim” />
< /bean>
   < /entry>
    <entry key-“1003”>
     <bean id=”s3” class=”com.nit.spring.Student”>
       <property name=”rollno” value=”1003” />
        <property name=”name” value=”David” />
< /bean>
< /entry>
< /map>
< /property>
< /bean>
< /beans>

————————————————————

ExecuteBean

public class ExecuteBean
{
     public static void main (String args[]) throws Exception
     {
BeanFactory beanfactory=new XmlBeanFactory (new FileSystemResource (“collection.xml”));
       College college= (College) beanfactory.getBean (“c”);
       Map<Integer,Student> students=college.getStudents ();
       Set <Integer> keys=students.keySet (); //HashSet object created
               int count=1;
             for (Integer k:keys)
             {
                 Student s=(Student) students.get (k);
                 System.out.println (“Student”+count+”details…”);
                 s.displayStudentDetails ();
                 count++;
             }
     }
}

Que: -Properties example

  1. HelloBean.java
  2. bean.xml
  3. Main.java
package com.nit.spring;
import java.util.Propertis;

public class HelloBean
{
     Properties properties;
     public void setProperties (Properties properties)
     {
         this.properties=properties;
     }
       public Properties getProperties ()
       {
           return properties;
       }
}

————————————————————

bean.xml

<beans>
     <bean name=”h” class=”com.nit.spring.HelloBean”>
           <property name=”properties”>
                 <props> //indicating the container to create the Properties object
                         <prop key=”name”>Rama< /prop>
                         <prop key=”address”>Hyderabad< /prop>
                 < /props>
           < /property>
     < /bean>
< /beans>

————————————————————

public class Main
{
     public static void main (String s []) throws Exception
     {
         BeanFactory beanfactory=new XmlBeanFactory (new FileSystemResource (“collection.xml”));
         HelloBean myBean= (HelloBean) beanfactory.getBean (“h”);
         Properties p=myBean.getProperties ();
         Set (String> keys=p.stringPropertiesNames () ;
         for (String key:keys)
         {
                 System.out.println (“key+”:”+p.getProperties (key));
         }
     }
}

previous-button-hisubmit-hi

Share Button

set based collection example.

previous-button-hisubmit-hi

Que: -set based collection example.

  1. College.java
  2. bean.xml
  3. ExecuteBean.java
  4. Student.java

College.java

package com.nit.spring;
import java.util.set;

public class College
{
private String name;
private Set <Student>students;
public College (String name)
{
this.name=name;
}
public void setStudents (Set students)
{
this.students=students;
}
public Set getStudents ()
{
return students;
}
}

————————————————————

Student.java

package com.nit.spring;

public class Student
{
private int rollno;
private String name;
public Student (int rollno, String name)
{
this.rollno=rollno;
this.name=name;
}
public void displayStudentDetails ()
{
System.out.println (“Rollno:”+ rollno);
System.out.println (“Name:”+ name);
}
}

————————————————————

bean.xml:

< ? xml version=”1.0” encoding=”UTF-8”?>
<beans>
xmlns= “http://www.springframework.org/shema/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-2.0.xsd”>
<bean id= “s1” class= “com.nit.spring.Student”>
<constructor-arg type= “int” index=”0” value=”1001” />
<constructor-arg value=”Rama” />
< /bean>
<bean id= “s2” class= “com.nit.spring.Student”>
<constructor-arg type= “int” index=”0” value=”1002” />
<constructor-arg value=”Rahim” />
< /bean>
<bean id= “s3” class= “com.nit.spring.Student”>
<constructor-arg type= “int” index=”0” value=”1003” />
<constructor-arg value=”David” />
< /bean>
<bean name= “c” class= “com.nit.spring.Student”>
<constructor-arg value=”Rama” />
<property name=”students”>
<set>
<ref bean=”s1” />
<ref bean=”s2” />
<ref local=”s3” />
<ref local=”s3” />
< /set>
< /property>
< /bean>
< /beans>

————————————————————

public class ExecuteBean
{
public static void main (String args[]) throws Exception
{
BeanFactory beanfactory=new XmlBeanFactory (new FileSystemResource (“collection.xml”));
College college= (College) beanfactory.getBean (“c”);
Set <Student> students=college.getStudents ();
int count=1;
for (Student s:students)
{
System.out.println (“Student”+count+”details…”);
s.displayStudentDetails ();
count++;
}
}
}

previous-button-hisubmit-hi

Share Button

How to configure setbased collection as dependency to a spring bean

previous-button-hisubmit-hi

 

Que: -How to configure setbased collection as dependency to a spring bean? Give example

Step 1: –In the spring bean make a list based or set based collection variable as dependency.

e.g.: –

public class College
{
List<Student> students;
Or
Set<Student> students;
----------------
----------------
}

Step 2: –Make use of <set> tag in the beans-configuration file.

Note: –In case of list based collection, duplicates are allowed. Whereas in case of set based collections duplicates are not allowed.

e.g.: –

<set>
<ref bean=”s1”/>
<ref local=”s2”/>
<ref local=”s3”/>
<ref local=”s4”/>
< /set>

In a spring application multiple configuration files. While specifying the elements to a collection we make use of <ref> tag. For this tag we can use “local” attribute instead of “bean” attribute if the dependency bean is also configured in the same xml file. If the dependency bean is configured in another configuration file, “local” attribute can’t be used, we must use “bean” attribute only.

Que: -How to inject a map based collection into a spring bean?

Step 1: –In the spring bean class declare “java.util.Map” type variable as dependency.

e.g.: –

public class College
{
Map<Integer, Student> student;
-------------------
-------------------
}

Step 2: –Make use of <map> tag in spring configuration file as given in the example case.

e.g.: –

<map>
<entry key=”1001”>
<bean id=”s1” class=”com.nareshit.Students”>
<property name=”rollno” value=”1001”>
<property name=”name” value=”Rama”>
< /bean>
< /entry>
---------------
---------------
< /map>

previous-button-hisubmit-hi

Share Button

Spring container call the instanceFactory() of the spring bean

previous-button-hisubmit-hi

 

Que: -Modify the above application in such a way that spring container call the instanceFactory() of the spring bean.

instance Factorymethod example

  1. beans.xml
  2. HelloBean.java
  3. ExecuteBean.java

 

Note: –ExecuteBean.java and HelloBean.java from previous application expect making getInstance () method as non-static method.

beans.xml”

<beans>
<bean name=”hb” class=”HelloBean” >
<constructor-arg value=”hello”>
< /bean>
<bean name=”hb1” class=”HelloBean” factory-bean=”hb” factory-method=”getInstance”/>
< /beans>

Que: -How to specify same user-defined initialization method and destruction method for all the beans of the spring application?

By using “default-init-method” and “default-destroy-method” attributes of <beans> tag we specify custom initialization and destruction methods for the multiple spring beans.

e.g.: -
<beans------default-init-method=”init”
default-destroy-method=”destroy”>

Que: -How to inject a list of based collection into a spring bean?

Step 1: –The spring bean class declare “java.util.List” type variable as dependency.

e.g.: –

public class College
{
List<Student> students;
----------
----------
}

Step 2: –Make use of one of the four collection configuration elements in bean configuration file i.e. use <list> tag.

e.g.: –

<list>
<ref bean=”s1”/>
<ref bean=”s2”/>
<ref bean=”s3”/>
< /list>

list based injection

  1. student.java
  2. college.java
  3. springApplication.java
  4. beans.xml

In this example college is the dependent bean collection of student bean is the dependency.

student.java”

package com.nareshit.spring;
public class student
{
Private int rollno;
Private String name;
public Student(int rollno, String name)
{
this.rollno=rollno;
this.name=name;
}
public void displayStudentDetails()
{
System.out.println(“Rollno:”+rollno);
System.out.println(“Name:”+name);
}//business method
}

College.java”

package com.nareshit.spring;
import java.util.list;
public class College //dependent
{
private String name; //dependency 1
private List<student> students; //dependency 2
private College(String name)
{
this.name=name;
}//for constructor injection
public void setStudents (List<student> students)
{
this.students=students;
}//fpr setter injection
public List<student> getStudents()
{
return students;
}//business method
}

beans.xml”

<beans>
<bean id=”s1” class=”com.nareshit.spring.Student”/>
<constructor-arg value=”101” />
<constructor-arg value=”Rama” />
< /bean>
<bean id=”s2” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”102” />
<constructor-arg value=”Rohini” />
< /bean> 
<bean id=”s3” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”103” />
<constructor-arg value=”David” />
< /bean> 
<bean id=”c” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”NIT” />
<property name=”students” />
<list>
<ref bean=”s1” />
<ref bean=”s2”/>
<ref bean=”s3”/>
< /list>
< /property>
< /bean> 
< /beans>

SpringApplication.java”

import com.nareshit.spring.College;
import com.nareshit.spring.Student;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.FileSystemResource;
import java.util.List;

class SpringApplication
{
public static void main(String [] args)
{
Resource resource=new FileSystemResorce (“beans.xml”);
BeanFactory =new XmlBeanFactory (resource);
Object o=factory.getBean (“c”);
College c1= (college) o;
List <student> listOfStudent=c1.getStudents (); //business method call
int count=1;
for (Student s:listOfStudents)
{
System.out.println(“Student”+count+”details…”);
s.displayStudentDetails ();
count ++;
}
} //main
} //class

previous-button-hisubmit-hi

Share Button

important methods of BeanFatory interface

previous-button-hisubmit-hi

 

Que: -What are the important methods of BeanFatory interface?

  1. object getBean (String)
  2. object getBean (String, Class)
  3. boolean isSingleton (String name)
  4. boolean isPrototype (String name)
  5. boolean containtsBean (String name)
  6. String [] getAliases (String name)

A spring bean can have more than one name. Those names are known as its aliases.by calling getAliases () method we can get all the alias names of the spring bean.

e.g.: -
<bean name=”hb1, hb2, hb3” class=”HelloBean”>
String s [] =container.getAliases (“hb1”);
for (int i=0; i<s.lenght; i++)
System.out.prinln (s[i]);

Output: -
hb2

hb3

Spring bean in the application is a singleton or not use can find out by calling isSingleton() method on the bean container. The following statements prints true for a bean as a spring bean is by default singleton in a spring container.

System.out.println(container.isSingleton(“hb1”));

  • isProtype () method returns false for a bean unless we change its scope to prototype.
  • constantBean () method returns true if the bean definition is found in the bean configuration file with that name.

System.out.println (container.constantBean(“hb1”));

For bean instantiation overloaded getBean() method is used as follows: –

HelloBean hb= (HelloBean) container.getBean (“hb1”, HelloBean.class);

Que: – Example spring application on creating a bean instance using static factory() method?

Some java classes can be instantiated only though their static factory methods. In such a case, we should indicate to the spring container about the same by using “factory-method” attribute of <bean> tag.

To this attribute, we need to specify the factory method name as the value.

Factorymethodinstantiation

  1. HelloBean.java
  2. ExecuteBean.java
  3. beans.xml

HelloBean.java”

public class HelloBean
{
private String message;
public HelloBean (String m);
{
message =m;
}
public static HelloBean getInstance()
{
System.out.println (“In factory method”);
HelloBean hb= new HelloBean (“Instantiated from static factory method”);
return hb;
} //user defined static factory method
public void displayMessage()
{
System.out.println (message);
}
}

beans.xml”

<beans>
<bean name=”hb1” class=”HelloBean” factory-method=”getInstance”/>
< /beans>

ExecuteBean.java”

class ExecuteBean
{
p
{
xmlBeanFactory factory=new XmlBeanFactory (newFileSystemResource (“beans.xml”));
HelloBean hb=(HelloBean) factory.getBean (“hb1”);
Hb.displayMessage ();
}
}

previous-button-hisubmit-hi

Share Button

Role of java interfaces in spring application development

previous-button-hisubmit-hi

 

Que: -What is the role of interfaces in java applications?

Coding to the interfaces is preferable to coding classes. Interfaces provide loose coupling between service requester object and service provider object. As a result service provider changing any code in the service requester/service utilizer object. This is known as seamless system development.

Que: -What is the roll of java interfaces in spring application development?

In non-spring applications, interfaces in are useful. But somewhere, the implementation object of the interfaces has to be hardcoded in the application. In a spring application even that also not needed. If we have interfaces as dependency variable types, dependent object is loosely coupled with dependency object. Without changing the source code of the dependent object, we can swap-in and swap-out the dependency object class declaratively without hardcoding them. Therefor we say that as far as possible dependencies should be interfaces to promote loose coupling between application object.

Que: -Develop a spring application in which setter injection is implemented and loose coupling is also implemented between dependent and dependency?

Loose coupling application

  1. CustomerBean.java (dependent)
  2. Menu.java (dependency interface)
  3. BlueFoxRestaurantBean.java
  4. AdityaRestaurantBean.java
  5. SpringApplication.java
  6. beans.xml

 

Menu.java”

package com.nareshit.spring;
public interface menu
{
public abstract void provideFoodService ();
}

BlueFoxRestaurantBean.java”

package com.nareshit.spring;
public class BlueFoxRestaurantBean implements Menu
{
public void provideFoodService()
{
System.out.println (“Providing very good food service”);
} 
}

AdityaRestaurantBaen.java”

package com.nareshit.spring;
public class AdityaRestaurantBean implements Menu
{
public void provideFoodService()
{
System.out.println (“Providing excellent food service”);
} 
}

CustomerBean.java”

package com.nareshit.spring;
public class CustomerBean
{
Menu menu; //dependency
public void setMenu(Menu menu)
{
this.menu=menu;
}
public void expectFoodService()
{
System.out.println(“customer expecting food service”);
menu.provideFoodService(); //inter-bean communucation
} 
} //dependent bean

beans.xml”

<beans>
<bean id=”r1” class=”com.nareshit.spring.BlueFoxRestaurantBean”/>
<bean id=”r2” class=”com.nareshit.spring.AdityaRestaurantBean”/>
<bean id=”c” class =”com.nareshit.springCustomerBean”>
<property name=”menu” ref=”r1”/>
< /bean>
< /beans>

springapplication.java”

import com.nareshit.spring.Menu;
import com.nareshit.spring.CustomerBean;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.FileSystemResource;

public class SpringApplication
{
public static void main(String [] args)
{
Resource resource=new FileSystemResorce (“beans.xml”);
BeanFactory =new XmlBeanFactory (resource);
CustomerBean cb= (CustomerBean)factory.getBean (“c”);
Cb. expectFoodService ();
} //main
} //class

previous-button-hisubmit-hi

Share Button

How to inject a list based collection into a spring bean

previous-button-hisubmit-hi

 

Que: -How to inject a list based collection into a spring bean? Give example

listbasedinjection

  1. student.java
  2. college.java
  3. springApplication.java
  4. beans.xml

In this example college is the dependent bean collection of student bean is the dependency.

  1. student.java”
package com.nareshit.spring;
public class student
{
Private int rollno;
Private String name;
public Student(int rollno, String name)
{
this.rollno=rollno;
this.name=name;
}
public void displayStudentDetails()
{
System.out.println(“Rollno:”+rollno);
System.out.println(“Name:”+name);
}//business method
}

2. “College.java”

package com.nareshit.spring;
import java.util.list;
public class College //dependent
{
private String name; //dependency 1
private List<student> students; //dependency 2
private College(String name)
{
this.name=name;
}//for constructor injection
public void setStudents(List<student> students)
{
this.students=students;
}//fpr setter injection
public List<student> getStudents()
{
return students;
}//business method
}

3. “beans.xml”

<beans>
<bean id=”s1” class=”com.nareshit.spring.Student”/>
<constructor-arg value=”101” />
<constructor-arg value=”Rama” />
< /bean>
<bean id=”s2” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”102” />
<constructor-arg value=”Rahim” />
< /bean> 
<bean id=”s3” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”103” />
<constructor-arg value=”David” />
< /bean> 
<bean id=”c” class=”com/nareshit.spring.Student”/>
<constructor-arg value=”NIT” />
<property name=”students” />
<list>
<ref bean=”s1” />
<ref bean=”s2”/>
<ref bean=”s3”/>
< /list>
< /property>
< /bean> 
< /beans>

4. “SpringApplication.java”

import com.nareshit.spring.College;
import com.nareshit.spring.Student;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.FileSystemResource;
import java.util.List;

class SpringApplication
{
public static void main(String [] args)
{
Resource resource=new FileSystemResorce (“beans.xml”);
BeanFactory =new XmlBeanFactory (resource);
Object o=factory.getBean (“c”);
College c1= (college) o;
List <student> listOfStudent=c1.getStudents (); //business method call
int count=1;
for(Student s:listOfStudents)
{
System.out.println(“Student”+count+”details…”);
s.displayStudentDetails ();
count ++;
}
} //main
} //class

previous-button-hisubmit-hi

Share Button

Spring bean scope

previous-button-hisubmit-hi

 

By default spring beans are singletons i.e. spring container creates only one instance of the spring bean irrespective of the no. of getBean() method calls on the spring container. To change this default nature of the spring container we make use of “scope” attribute of the <bean> tag and give “prototype” as its value. In such a case spring container creates one instance per getBean() method call even if we specify the same bean ‘id’.

e.g.: -
<bean id=”hb” class=”HelloBean” scope=”prototype”>

Observe the output of the following application?

Constructorambiguity

  1. Employee.java
  2. springApplication.java
  3. Beans.java

1. “Employee.java”

public class Employee
{
string name;
string designation;
float salary;
Employee(String name, String designation)
{
this.name=name;
this.designation=designation;
}
Employee (float salary, Stirng name)
{
this.salary = salary;
this.name=name;
}
public void displayEmployeeDetails()
{
System.out.println (“name:”+designation);
System.out.println (“designation:”+designation);
System.out.println (“salary:”+salary);
}
}

SpringApllication.java”

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

class SpringApplication
{ 
public static void main(String [] args)
{
Resource resource=new FileSystemResource (“beans.xml”);
BeanFactory =new XmlBeanFactory (resource);
Employee e= (Employee) factory.getBean (“eb”);
e.displayEmployeeDetails ();
}
}

beans.xml”

<beans>
<bean id=”eb” class=”Employee”>
<constructor-arg value=”5000.50”/>
<constructor-arg value=”Rama”/>
< /bean>
< /beans>

Note: –For each parameter of the constructor of the spring bean we have to use one <constructor-arg> tag while configuring the bean in bean configuration file.

Output: –

name : 5000.50

designation : Rama

salary : 0.0

Reason for the above unexpected output is, spring container treats <constructor-arg> values as spring first. If spring container encounters the constructor that takes strings as argument, it uses that kind of constructor while instantiating the spring bean without appropriate conversion. Because of such springframework’s behavior constructor ambiguity occurred while instantiating the Employee bean.

To resolve this constructor ambiguity we make use of two attributes of <constructor-arg> tag: –

  1. index
  2. type

Index specifies the parameter number in the parameter list of the constructor but the numbering starts from.

Type specifies the data of the constructor parameter.
beans.xml //modified beans file

<beans>
<bean id=”eb” class=”Employee”>
<constructor-arg value=”5000.50” type =”float” index=”0”/>
<constructor-arg value=”Rama” type=”java.lang.String” index=”1”/>
< /bean>
< /beans>

previous-button-hisubmit-hi

Share Button

Spring application to explore the life cycle of a spring bean

previous-button-hisubmit-hi

 

Lifecycleapplication

  1. AccountBean.java
  2. SpringApplication.java
  3. beans.xml

1. “AccountBean.java”

public class AccountBean
{
Float amount; //dependency
public AccountBean()
{
System.out.println(“bean instance created”);
}
public void getAmount (float amount);
{
this.amount = amount;
System.out.println(“bean dependency is provided with setter injection”);
}
public void ownInit()
{
System.out.println(“Resource are allocated to the spring bean here”); 
}//custom init method
public void ownDestroy()
{
System.out.println(“Resource are released”);
} //custom destroy method
public void calculateInterest()
{
Float interest=amount*0.05f;
System.out.println(“Interest :Rs:”+interest);
}//business method
}

2. “beans.xml”

<bean>
<bean name=”ab” class=”accountBean” 
init-method=”owninit” destroy-method=”ownDestroy”><property name=”omount” value=”5000” />
< /bean>
< /beans>

3. SpringApplication.java

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;//import org.springframework.beans.factory.support.DefaultSingletonBean

class SpringApplication
{
public static void main(String [] args)
{
Resource resource=new ClassPathResorce (“beans.xml”);
XmlBeanFactory sc=new XmlBeanFactory (resource);
AccountBean accountBean= (AccountBean) sc.getBean (“ab”);
accountBean.calculateInterest();
sc.destroySingletons(); //if not runs normally,use following
// ((DefaultSingletonBeanRegistry) factory).destroySingletons ();
}
}

previous-button-hisubmit-hi

Share Button