1

I'm using Spring to auto-wire beans for configuration. Some parameters come from a properties file:

<bean id="mydb" class="myproject.mydb" autowire="constructor">
    <constructor-arg name="host" value="${mydb.host}" />
    <constructor-arg name="db" value="${mydb.db}" />
    <constructor-arg name="user" value="${mydb.user}" />
    <constructor-arg name="password" value="${mydb.password}" />
</bean>

Is there a way to auto-wire these properties based on the bean id so that I would just have to write the following?

<bean id="mydb" class="myproject.mydb" autowire="constructor" />

Edit: The point of this is to not have to explicity specify the non-bean constructor arguments. I want Spring to automatically check the properties for beanId.constructorArgName

bcoughlan
  • 25,987
  • 18
  • 90
  • 141
  • I finally understood what you are expecting. You expect Spring to guess he must uses `mydb.host` property for your bean `mydb`. I'm not aware of such a feature – yunandtidus Oct 15 '14 at 12:44

4 Answers4

1

In your class myproject.mydb

 @Autowired
 public mydb(@Value("mydb.host") String host,  ...){...}
yunandtidus
  • 3,847
  • 3
  • 29
  • 42
1

To achieve exactly what you want, I think you'd need to implement a BeanPostProcessor and provide your custom wiring logic (where you read the .properties file) in postProcessBeforeInitialization. The bean name is available to that method, but there are multiple problems with this. The first is that argument names are not necessarily available at runtime, so indexes might be a better option. The second is that you already have an instantiated bean (so a default constructor would need to exists), and you'd instantiate another, throwing the first one away which is wasteful. To use the instance that already exists, you'd need to wire it by properties, not constructor, which violates encapsulation and is not what you asked. The third is that it's not at all obvious what is going on. So, all in all, you are probably better off avoiding this completely.

Community
  • 1
  • 1
kaqqao
  • 12,984
  • 10
  • 64
  • 118
0

As per your question, the only way Property values can be injected to the constructor is through the XMLfile as done above or using the @Value("${some.property}") annotation.

Refer this for more info

Community
  • 1
  • 1
Vishnu
  • 1,011
  • 14
  • 31
0

Use @Value("property key") annotation. look at eg.: http://java.dzone.com/articles/autowiring-property-values

Chowdappa
  • 1,580
  • 1
  • 15
  • 31