Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autowiring only certain arguments of a constructor

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?

like image 529
davioooh Avatar asked Jul 05 '12 14:07

davioooh


2 Answers

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.

like image 143
Luciano Avatar answered Nov 12 '22 12:11

Luciano


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>
like image 33
Mike Clark Avatar answered Nov 12 '22 12:11

Mike Clark