I have a static method I have no control over: MyUtils.getServiceURL() which returns a URL. I need to extract just the port from this URL to set a property on a bean:
<bean id="myBean>
<property name="defaultPort" value="?????"/>
</bean>
I can get the string value of the URL as a bean like this:
<bean id="serviceURL" class="MyUtils" factory-method="getServiceURL" />
I’m probably just going to write a method to parse the URL in myBean and extract the port. I was wondering if there was a way to avoid having to do this, and configure this directly in the spring context?
No need for custom classes, or parsers. Remember, a bean is just a class with get/is/set methods. A
java.net.URLclass qualifies as such.Solution: Use a
java.net.URLas a Spring-configurable bean and call it’sgetPortmethod.Remember, in Spring, you can wire anything as a bean very easily so long as it sports methods using the get/is/set Bean convention. The java.net.URL class does such a thing.
** warning ** I’m just typing this out of my a$$, you’ll have to check for any syntax shenanigans that I might be introducing in this Spring-config pseudo-code. One thing that is certain is that the concept will work with Spring 2.5 and that it relies on the
utilschema.If you are using an older version of Spring, you’ll have to use a
PropertyPathFactoryBean. If you are using Spring 3.0, you’ll want to use Spring expression language (EL), but I can’t comment on the later since I’m not familiar with Spring 3.0.In java:
In Spring:
There might be a way to consolidate all these four expressions into three or less, don’t know if that will improve readability, though. The concept remains the same, though. Treat a
java.net.URLinstance as a bean, set its URL via its constructor, and get a hold (via Spring) of itsgetPort()method.** edit **:
If you are using Spring 2.5 you can create an inline groovy bean that does all that for you. I’ve seen people doing that as integration glue to get rid of multitude of temp Spring bean place holders. That’s the best choice IMO when you need to define a class (when it’s simpler than just using Spring tags) and when you know such a class won’t be used outside of Spring wiring of things.