Dónal Dónal - 1 year ago 102
Java Question

How can I inject a property value into a Spring Bean which was configured using annotations?

I have a bunch of Spring beans which are picked up from the classpath via annotations, e.g.

public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {
// Implementation omitted

In the Spring XML file, there's a PropertyPlaceholderConfigurer defined:

<bean id="propertyConfigurer"
<property name="location" value="/WEB-INF/app.properties" />

I want to inject one of the properties from app.properites into the bean shown above. I can't simply do something like

<bean class="com.example.PersonDaoImpl">
<property name="maxResults" value="${results.max}"/>

Because PersonDaoImpl does not feature in the Spring XML file (it is picked up from the classpath via annotations). I've got as far as the following:

public class PersonDaoImpl extends AbstractDaoImpl implements PersonDao {

@Resource(name = "propertyConfigurer")
protected void setProperties(PropertyPlaceholderConfigurer ppc) {
// Now how do I access results.max?

But it's not clear to me how I access the property I'm interested in from

Answer Source

You can do this in Spring 3 using EL support. Example:

public void setDatabaseName(String dbName) { ... }

public void setKeyGenerator(KeyGenerator kg) { ... }

systemProperties is an implicit object and strategyBean is a bean name.

One more example, which works when you want to grab a property from a Properties object. It also shows that you can apply @Value to fields:

private String githubOauthClientId;

Here is a blog post I wrote about this for a little more info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download