Thursday, August 28, 2014

Dependency injection in Spring

Injecting beans

@org.springframework.beans.factory.annotation.Autowired
@javax.inject.Named("beanId")


Injecting properties file values

@org.springframework.beans.factory.annotation.Value("${key.in.file}")
private String hostName;

Injecting util: list, set, map

@javax.annotation.Resource(name="mySet")
private Set<Action> allTrafficActions;

set is defined in xml:
<util:set id="mySet" set-class="java.util.HashSet"
value-type="com.api.types.Action">
<value>DATA</value>
<value>SMS_MO</value>
<value>MMS_MO</value>
</util:set>
com.api.types.Action is enum.


Inject list from properties file:
internal.operators.ids=10005,216,217
you can inject it with expression:
@org.springframework.beans.factory.annotation.Value("#{'${internal.operators.ids}'.split(',')}")
private List<String> internalOperators;

Use @Value as optional.
There is no need to be specified/defined in properties file.
E.g.
@Value("${external.createsim:true}")
boolean notifyExternalHandler = true;


Use property as message template
template.file=/opt/polite/{0}.prov

In code inject value and use MessageFormater to replace {0}:
@Value("${template.file}")
String postpaidFilename = "/opt/{0}.prov";

String filename = java.text.MessageFormat.format(postpaidFilename, "123");

Result filename is /opt/polite/123.prov


Ref:
http://kh-yiu.blogspot.com/2013/08/spring-injecting-properties-file-values.html
http://samaratips.blogspot.com/2011/07/spring-autowired.html
https://stackoverflow.com/questions/12576156/reading-a-list-from-properties-file-and-load-with-spring-annotation-value
http://www.captaindebug.com/2012/01/autowiring-using-value-and-optional.html
http://www.baeldung.com/2012/02/06/properties-with-spring/

No comments:

Post a Comment