Auto-authorization of only certain constructor arguments

Is it possible in AutoSign only specific constructor arguments in Spring?

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 would like the object to MyDaobe auto-updated, and explicitly define the argument name. Is it possible?

Defining a bean using XML requires manually defining all the arguments?

+5
source share
4 answers

You cannot do this with a constructor created automatically, as 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 do not show that its public setter is in its class.

+3
source

, , MyDao, , name. ,

<bean class="MyClass">
  <constructor-arg value="Hardcoded string value for the name" />
  <constructor-arg ref="myDaoInstance" />
</bean>

<bean class="MyDao" id="myDaoInstance>
  //relevant config
</bean>
+2

Looks like you should add @Autowired to MyDao dao; then change the constructor to just take the name param. You can automatically access MyDao

0
source

All Articles