Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject a value to bean constructor using annotations

My spring bean have a constructor with an unique mandatory argument, and I managed to initialize it with the xml configuration :

<bean name="interfaceParameters#ota" class="com.company.core.DefaultInterfaceParameters">   <constructor-arg>     <value>OTA</value>   </constructor-arg>  </bean> 

Then I use this bean like this and it works well.

 @Resource(name = "interfaceParameters#ota")  private InterfaceParameters interfaceParameters; 

But I would like to specify the contructor arg value with the annocations, something like

 @Resource(name = "interfaceParameters#ota")  @contructorArg("ota") // I know it doesn't exists!  private InterfaceParameters interfaceParameters; 

Is this possible ?

Thanks in advance

like image 602
tbruyelle Avatar asked Nov 17 '10 10:11

tbruyelle


People also ask

Which annotation is used to inject property values into beans?

The Javadoc of the @Value annotation.

Which annotation is used to inject one bean into another bean automatically?

Enabling @Autowired Annotations The Spring framework enables automatic dependency injection. In other words, by declaring all the bean dependencies in a Spring configuration file, Spring container can autowire relationships between collaborating beans.


1 Answers

First, you have to specify the constructor arg in your bean definition, and not in your injection points. Then, you can utilize spring's @Value annotation (spring 3.0)

@Component public class DefaultInterfaceParameters {      @Inject     public DefaultInterfaceParameters(@Value("${some.property}") String value) {          // assign to a field.     } } 

This is also encouraged as Spring advises constructor injection over field injection.

As far as I see the problem, this might not suit you, since you appear to define multiple beans of the same class, named differently. For that you cannot use annotations, you have to define these in XML.

However I do not think it is such a good idea to have these different beans. You'd better use only the string values. But I cannot give more information, because I dont know your exact classes.

like image 102
Bozho Avatar answered Sep 18 '22 14:09

Bozho