Need of method
replacement: Suppose
some bug is identified during last phase of testing, analysed the same and
found that the root cause is third party jar/API. To rectify the same we need
to look for update on this API. Since our testing is in last phase and there is
no time to analyse the impact of using updated API in our system. We can use
this feature of spring.
Simple Requirement:
Now
there is a requirement to wish a customer saying “Dear Customer, Good
Morning/Good Afternoon/Good Evening….”, based on the customer login time.
package com.thirdpartyapi;
import java.util.Calendar;
public class WishCustomer {
public void sayWishes() {
Calendar cal = Calendar.getInstance();
int currHour = cal.get(Calendar.HOUR_OF_DAY);
if(currHour < 12) {
System.out.println("Dear Valued Customer, Good Morning.....");
} else if(currHour >= 12 && currHour < 18) {
System.out.println("Dear Valued Customer, Good Afternoon.....");
} else if(currHour >= 18 && currHour < 24) {
System.out.println("Dear Valued Customer, Good Evening.....");
}
}
}
|
Spring configuration:
<bean id=”wishCustomer” class="com.thirdpartyapi.WishCustomer"
/>
|
The
above code given by third party API has clearly satisfied the requirement. Now
the business has enhanced and got the client over the world.
Problem: Irrespective of the user time zone,
the above class wishes the customer based on the application server time zone.
Solution: Need to override sayWishes() method
of WishCustomer class alone without impacting of
other logic in this API.
package com.saywish;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.TimeZone;
import
org.springframework.beans.factory.support.MethodReplacer;
public class WishCustomerReplacer implements MethodReplacer {
public Object reimplement(Object arg0, Method arg1, Object[]
arg2) throws Throwable {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("IST"));
//IST is hard coded,
can be pass dynamically based on user location
int currHour = cal.get(Calendar.HOUR_OF_DAY);
if(currHour < 12) {
System.out.println("Dear Valued Customer, Good Morning.....");
} else if(currHour >= 12 && currHour < 18) {
System.out.println("Dear Valued Customer, Good Afternoon.....");
} else if(currHour >= 18 && currHour < 24) {
System.out.println("Dear Valued Customer, Good Evening.....");
}
return null;
}
}
|
The
yellow highlighted is the customization, setting the time zone value to the Calendar
instance based on the user country time zone.
Spring configuration
for Method Replacer:
<bean id="wishCustomer" class="com.thirdpartyapi.WishCustomer" >
<replaced-method name="sayWishes"
replacer="wishCustomerReplacer" />
</bean>
<bean id="wishCustomerReplacer" calss="com.saywish.WishCustomerReplacer"
/>
|
No comments:
Post a Comment