java - Static Utility Class in spring 3 application -
is violation if go ahead utility methods static rather depending on di of spring?
i have maintain hashmap below:
private static map<string,jmsmessage> messagemap = collections.synchronizedmap(new hashmap<string,jmsmessage>());
messagemap can accessed multiple threads. have utility methods play around messagemap. made class final , declared utility methods static. violation according spring ioc?
i argue that, though possible , work correctly in spring ioc, violation of principals of inversion-of-control.
it better use singleton bean managed ioc use static field, this
@component @scope(configurablebeanfactory.scope_singleton) public class simplemessagemanager implements messagemanager { private map messagemap = collections.synchronizedmap(new hashmap()); @override void addmessage(...) { ... } @override void getmessage(...) { ... } }
you inject messagemanager this:
public class somebean { @resource messagemanager messagemanager; }
there many reasons why sticking ioc approach better:
- you may need more 1 instance in future.
- you can mock out messagemanager interface in unit tests.
- (related 2) if use static fields, cannot sure of state of messagemap during testing. becomes more complicated if start running tests in parallel (a standard option in maven)
as aside, recommend not use collections.synchronizedmap. have considered using concurrenthashmap instead?
Comments
Post a Comment