Monday, March 30, 2009

Spring ApplicationContextAware

If you need to get Spring Application Context don't initialize it. This operation could be slow. The better way is to allow Spring to inject its context:


public class MyClass implements ApplicationContextAware{
private ApplicationContext context;

...
public void setApplicationContext(ApplicationContext applicationcontext) throws BeansException {
this.context= applicationcontext;
}

}

Thursday, March 26, 2009

FreeMarker & HashMap

I had the following hash map

ConcurrentHashMap<String, AtomicLong> requestPerOperation;


In order to iterate the content in free marker template use:

<#list requestPerOperation?keys as key>
<li>${key} : ${statistics.operationsRequests[key]}</li>
</#list>

CollectionUtils

The better way to define collections:



public class CollectionUtils {

public static <T> T[] ar(T... ts) {
return ts;
}

public static <T> Set<T> set(T... ts) {
return new HashSet<T>(Arrays.asList(ts));
}

public static<K,V> Map<K, V> map(K[] keys, V[] values) {
Map<K,V> result = new HashMap<K,V>();
int i = 0;
for ( K key : keys ){
if ( values.length > i ){
result.put( key, values[i++] );
} else {
result.put (key, null);
}
}
return result;
}

}


It's easier to initialize collections. Exmaple

Map<String, Object> debugObjects =
map(ar ( "statistics", "usersCache", "templateConfig", "throttler" ),
ar ( statistics , usersCache , templateConfig , throttler )
);


Borrowed from here