autowire

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值