Java & J2EE Page 4 - The Spring Framework: Understanding IoC |
The application I will develop in this section is a Compound Interest calculator. The values to be calculated will be "injected" via Constructor Injection. The application consists of three files:
Let's start with the class for the CompoundInterestBean. Just as the name suggests, it is a bean with setters and getters for Principle, Rate and Time. There are two extra methods: calculate, that calculates the interest; and getInterest, that returns the interest calculated. package org.me; class CompoundInterestBean { float years; float principle; float rate; CompoundInterestBean(){ } public void setYears(float years){ this.years=years; } public float getYears(){ return years; }
public void setPrinciple(float principle){ this. principle = principle; } public float getPrinciple(){ return principle; }
public void setRate(float rate){ this. rate=rate; }
public float calculate(){ return (float)((principle*(Math.pow(1+(rate/100)),time))-1); } public float getInterest(){ return calculate(); }
} Next comes the beans.xml. It contains the declarations for the constructor injection. Since there is more than one argument, there are multiple <constructor-arg> elements. <beans> <bean id=”CompoundInterestBean” class=”org.me. CompoundInterestBean”> <constructor-arg> <value>10000.00<value> </constructor-arg > <constructor-arg > <value>10.00<value> </ constructor-arg > <constructor-arg> <value>9.50<value> </constructor-arg > </bean> <beans> Next is the client class that calls the bean to calculate the interest. import java.io.*; import org.springframework.beans.factory.*; import org.springframework.beans.factory.xml.*; import org.springframework.core.io.*; public class Client { public static void main(String args[]) throws Exception { try { System.out.println("please Wait."); Resource res = new ClassPathResource("beans.xml"); BeanFactory factory = new XmlBeanFactory(res); CompoundInterestBean interest= (CompoundInterestBean)factory.getBean(“CompoundInterestBean”); System.out.println(interest.getInterest()); } catch(Exception e1) { System.out.println(""+e1); } } } To run this application successfully you will need the Apache Commons Library. That completes this discussion on how to use the forms of IoC with the Spring Framework. However, it opens up certain other questions. For example, can the IoC work for accessing data from database or other data sources? These questions will be the focus of discussion in the next part. Till then…
blog comments powered by Disqus |
|
|
|
|
|
|
|