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?
And this can be done either by using the @Autowired annotation or the @Value annotation. You use the @Autowired notation when the constructor argument is another Object, while the @Value annotation comes in handy when the contructor argument can easily be evaluated using Spring expression.
Spring container looks at the properties of the beans on which autowire attribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exists, a fatal exception is thrown.
You can apply @Autowired to constructors as well. A constructor @Autowired annotation indicates that the constructor should be autowired when creating the bean, even if no <constructor-arg> elements are used while configuring the bean in XML file.
Autowiring using property type. Allows a property to be autowired if exactly one bean of property type exists in the container. If more than one exists, it's a fatal exception is thrown, which indicates that you may not used byType autowiring for that bean.
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;
}
// ...
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With