Muel
Muel

Reputation: 4425

Property expansion with PropertiesFactoryBean

I wish to expose a Properties Spring bean whose values have been expanded via the typical property expansion mechanism. I'm using Spring 3.1. Let me digress.

Given the following properties file:

server.host=myhost.com
service.url=http://${server.host}/some/endpoint

And this portion of Spring XML config file:

<bean id="appProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
  <property name="locations">
    <list>
      <value>classpath:default.properties</value>
    </list>
  </property>
</bean>

<context:property-placeholder properties-ref="appProperties" />

I can write the following working code:

@Component
public class MyComponent {

  @Autowired
  @Qualifier("appProperties")
  private Properties appProperties;

  @Value("${service.url}")
  private String serviceUrl;

  // remainder omitted

}

The only problem is that if I obtain the service.url value from appProperties I get http://${server.host}/some/endpoint - ie the value is unexpanded. However, if I get the value of service.url from serviceUrl, the value has been expanded: http://myhost.com/some/endpoint.

Does anyone know of a good way to expose a Properties instance as a Spring bean whose values have been expanded?

Alternatively, if anyone can point me to a Spring bean (must be Spring 3.1) that will do the expansion for me, I'll accept this too! (Interestingly, if you manually pull the property values from the Environment or PropertySource you'll find that these too are unexpanded.)

Thanks, Muel.

Upvotes: 3

Views: 4641

Answers (1)

Jason
Jason

Reputation: 916

I'm pretty late to this, but it's been viewed enough times that i figured it warranted a quick response. What you're seeing is an artifact of how Spring handles property expansion. When the need for property expansion is found, only previously loaded sources are checked, not the currently loading property source. When the file loads, there are no previous sources, so ${server.host} does not expand. When you later reference ${server.url} via the @Value annotation, the property file source is loaded and can be searched as you expected. This is why the @Value annotation gets full expansion but the result queried from the property file does not.

Upvotes: 1

Related Questions