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:

  1. you may need more 1 instance in future.
  2. you can mock out messagemanager interface in unit tests.
  3. (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

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -