autowire

来源:互联网 发布:剑三交易怎么走淘宝 编辑:程序博客网 时间:2024/06/08 16:30
In all the examples so far, we have had to define explicitly, via the configuration file, how individualbeans are wired together. If you don’t like having to wire all your components together, you canhave Spring attempt to do so automatically. By default, automatic wiring is disabled. To enable it,you specify which method of automatic wiring you wish to use using the autowire attribute of thebean you wish to automatically wire.Spring supports four modes for automatic wiring: byName, byType, constructor, and autodetect.When using byName wiring, Spring attempts to wire each property to a bean of the same name. So, ifthe target bean has a property named foo and a foo bean is defined in the BeanFactory, the foo beanis assigned to the foo property of the target.When using byType automatic wiring, Spring attempts to wire each of the properties on the targetbean automatically using a bean of the same type in the BeanFactory. So if you have a propertyof type String on the target bean and a bean of type String in the BeanFactory, Spring wires the Stringbean to the target bean’s String property. If you have more than one bean of the same type, in thiscase String, in the same BeanFactory, Spring is unable to decide which one to use for the automaticwiring and throws an exception.The constructor wiring mode functions just like byType wiring, except that it uses constructorsrather than setters to perform the injection. Spring attempts to match the greatest numbers of argumentsit can in the constructor. So, if your bean has two constructors, one that accepts a String andone that accepts a String and an Integer, and you have both a String and an Integer bean in yourBeanFactory, Spring uses the two-argument constructor.The final mode, autodetect, instructs Spring to choose between the constructor and byType modesautomatically. If your bean has a default (no arguments) constructor, Spring uses byType; otherwise,it uses constructor.
原创粉丝点击