Is it possible in Spring to autowire only specific arguments of a constructor?
I defined:
<bean class="MyClass">
<constructor-arg name="name" value="object name" />
</bean>
With:
public class MyClass{
private String name;
private MyDAO dao;
@Autowired
public MyClass(String name, MyDao dao){
// assign...
}
// ...
}
Now I'd like MyDao
object to be autowired, while explicitly define name
argument.
Is it possible?
Defining a bean using XML requires to manually define all arguments?
You cannot do that with the autowired constructor, because it affects all parameters, but you can do this:
public class MyClass{
private String name;
@Autowired
private MyDAO dao;
public MyClass(String name){
// assign only name
}
// ...
}
It is similar to having a setter for the DAO but you don't expose that public setter it in your class.
If I read your question correctly, you are asking if you can wire in a MyDao instance that you have defined elsewhere in your context, and provide a hard-coded string value for the name parameter. If that is correct, you would configure your class like
<bean class="MyClass">
<constructor-arg value="Hardcoded string value for the name" />
<constructor-arg ref="myDaoInstance" />
</bean>
And elsewhere in your context file
<bean class="MyDao" id="myDaoInstance>
//relevant config
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With