Kevin Meredith
Kevin Meredith

Reputation: 41909

How to Autowire a 1-arg Object Constructor with Previously Autowired Object?

Given the following MyConstructorClass:

@Component
public class MyConstructorClass{

  MyObj var;
  public MyConstructorClass( MyObj constrArg ){
    this.var = var;
  }
...
}

How can I autowire a field that requires a constructor argument from a previously @Autowired field? Below is an example.

Note - this question, I believe, is similar to this one, except that my constructor argument is not a String. This code sample is slightly modified from this question.

@Service
public class MyBeanService{

  @Autowired               
  CustomObject customObj;                // no arguments to constructor

  @Autowired
  MyConstructorClass myConstructorClass; // requires `customObj` as an argument

  ....
}

How can I modify MyBeanService to properly construct myConstructorClass with customObj?

Upvotes: 1

Views: 1607

Answers (4)

Ricardo Veguilla
Ricardo Veguilla

Reputation: 3155

You just need to annotated the constructor of MyConstructorClass with @Autowired:

@Component
public class MyConstructorClass {
    final private CustomObject customObj;

    @Autowired 
    public MyConstructorClass(CustomObject customObj) {
        this.customObj = customObj;
    }
}

Another alternative, (without adding the @Autowired constructor to MyConstructorClass) is to use a @Configuration bean:

@Configuration
public class MyConfiguration {         

     @Bean 
     public CustomObject customObj() {
        return customObj;
     }

     @Bean 
     public MyConstructorClass myConstructorClass() {
        return new MyConstructorClass(customObj());
     }

     @Bean
     public MyBeanService myBeanService() {
         return new MyBeanService();
     }
 }

Upvotes: 2

sendon1982
sendon1982

Reputation: 11234

In the constructor, you can refer to other beans defined in Spring.

<bean id="myConstructorClass" class="package.MyConstructorClass">
    <constructor-arg index="0" ref="customObj"/>
</bean>

Upvotes: 0

Joe Terzieva
Joe Terzieva

Reputation: 21

If this is the only place you need to use that class could use @PostConstruct to instantiate itself. I think there is a better solution, but this is off the top of my head.

@Service
public class MyBeanService{

  @Autowired               
  CustomObject customObj;

  MyConstructorClass myConstructorClass;      

  @PostConstruct
  public void construct()
  {
    myConstructorClass = new MyConstructorClass(customObj);
  }
}

Upvotes: 0

Ker p pag
Ker p pag

Reputation: 1588

you can use the <constructor-arg> in your servlet

<bean id="myConstructorClass" class="package.MyConstructorClass">
        <constructor-arg>
            <bean class="package.CustomObject"/>
        </constructor-arg>
    </bean>

Upvotes: 0

Related Questions