Autowiring Property File Values Using @AutowiredProperty

Just recently, I was writing a little Spring-enabled http sampler (my next post), and I needed to introduce some values (hostname, port, ping url) from an outside configuration file. As I automatically used PropertyPlaceholderConfigurer (better known as <context:property-placeholder location="classpath:..." />), I noticed that only part of my problem was solved: the values taken from the configuration file could ONLY be injected into beans declared in my applicationContext.xml! This means that if I wanted to use Spring annotations for declaring beans (which I do), I had to write an "Adapter Beans", "Configuration Bean" or whatever name you want to call it... The Configuration bean would be declared in the xml file, and I'll @Autowire it to whatever other bean that needs that configuration... For every new property introduced anywhere in my application, I would need to add getter and a setter, which would be now visible throughout the application (not a problem for a small app', but still)... pain in the neck... Then I thought: what if I could @Autowire property file values the same way I autowired other beans?
 
Eager to start and inspired by the last annotation modification brain surgery that showed me how easy it is, in practice and not only in theory, to add custom annotation and then post-process them, I nearly sat down to start writing some code, when I found that very problem with the very solution on the Spring forums, again. Hurray!
 
This allowed me to write my code brieflier than ever, using:

  
@Service 
public class LatencySampler {

          @Autowired
          protected MBeanServerConnection conn;

          @AutowiredProperty(name="ping.url")
          protected String pingUrl;

           // ...  
}  


... with a config.properties similar to:

 

probee.hostname=hostsforever.com  
probee.jmx.port=8086 
ping.url=https://www.hostsforever.com/ping.jsp 



<p>Go’on, check it out on: http://forum.springsource.org/showthread.php?t=55183
 </p>

Thank you for your interest!

We will contact you as soon as possible.

Send us a message

Oops, something went wrong
Please try again or contact us by email at info@tikalk.com