In all the examples so far, we have had to define explicitly, via the configuration file, how individual beans are wired together. If you don’t like having to wire all your components together, you can have 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 the bean 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, if the target bean has a property named foo and a foo bean is defined in the BeanFactory, the foo bean is assigned to the foo property of the target. When using byType automatic wiring, Spring attempts to wire each of the properties on the target bean automatically using a bean of the same type in the BeanFactory. So if you have a property of type String on the target bean and a bean of type String in the BeanFactory, Spring wires the String bean to the target bean’s String property. If you have more than one bean of the same type, in this case String, in the same BeanFactory, Spring is unable to decide which one to use for the automatic wiring and throws an exception. The constructor wiring mode functions just like byType wiring, except that it uses constructors rather than setters to perform the injection. Spring attempts to match the greatest numbers of arguments it can in the constructor. So, if your bean has two constructors, one that accepts a String and one that accepts a String and an Integer, and you have both a String and an Integer bean in your BeanFactory, Spring uses the two-argument constructor. The final mode, autodetect, instructs Spring to choose between the constructor and byType modes automatically. If your bean has a default (no arguments) constructor, Spring uses byType; otherwise, it uses constructor.
autowire
最新推荐文章于 2024-09-25 11:56:42 发布