5

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?

Community
  • 1
  • 1
webmobileDev
  • 121
  • 1
  • 9

2 Answers2

5

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;
  }

  // ...
}
Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
3

You can either mark private data members with @Resource(name = "x") annotation OR wire them using constructor injection in the application context XML.

Annotations and XML configuration can be mixed in Spring. It need not be all or nothing.

<bean id="myClass" class="foo.bar.MyClass">
    <constructor-arg ref="yourArgRefHere"/> 
</bean>
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • but yourArgRefHere are some thing dynamic that i need to send by code – webmobileDev Apr 29 '12 at 08:39
  • It's hard to tell without more context. Maybe it shouldn't be under Spring's control; maybe you need a factory managed by Spring where you simply pass in the key. I don't know. – duffymo Apr 29 '12 at 13:04