Spring - autowire a class that have a constructor

autowired, java, spring

Solution

If you are using annotations you can apply @Autowired annotation to MyClass's constructor, which will auto wire beans you are passing to MyClass's special constructor. Consider following e.g.

public class MovieRecommender {

  @Autowired
  private MovieCatalog movieCatalog;

  private CustomerPreferenceDao customerPreferenceDao;

  @Autowired
  public MovieRecommender(CustomerPreferenceDao customerPreferenceDao) {
      this.customerPreferenceDao = customerPreferenceDao;
  }

  // ...
}

Problem

Possible Duplicate: Anyway to @Autowire a bean that requires constructor arguments? In my controller I want to use @Autowired to inject a class using the method / constructor autowiring. for example using: ``` @Autowired private InjectedClass injectedClass; ``` My problem is that the injected class injectedClass have a constructor, and I need to pass a variable to the constructor from the controller. How can I pass values to the constructors?

Original source

Related problems