Spring’s IoC is wonderful, and annotating classes for auto-configuration and wiring is exceptionally useful. But when you have a primitive value to set on an object, it can be tedious to manually define the bean in your context.xml. Here is an example:
@Service public class MainframeHealthService implements IMainframeHealthService { private String host; private String port; private String healthCheckEndpoint = "/mainframe/health"; public String getHealthStatus() { /* operation to check the status and return */ } }
Now, I could set the host as a bean in the context.xml:
<bean id="mainframeHealthSvc" class="main.MainframeHealthService" p:host="${mainframe.host}" p:url="${mainframe.port}"/>
But, here is another option — the Value annotation! It uses the same formatting as using the property placeholder but directly inside the class.
@Service public class MainframeHealthService implements IMainframeHealthService { @Value("${mainframe.host}") private String host; @Value("${mainframe.port}") private String port; private String healthCheckEndpoint = "/mainframe/health"; public String getHealthStatus() { /* operation to check the status and return */ } }
This does create a hard-coded dependency on that property. If it isn’t found by the container during bean processing, an IllegalArgumentException (“Could not resolve placeholder…”) is thrown.
Pingback: Using Java’s URLEncoder | Clear the Haze