Spring IOC容器基于配置文件装配Bean(1) ------设置autowire自动装配

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="carBean" class="com.spring.cn.config.autowire.CarBean"
        p:brand="宝马" p:price="350000"/>

    <bean id="carBean2" class="com.spring.cn.config.autowire.CarBean"
          p:brand="宝马" p:price="350000"/>

    <bean id="addressBean" class="com.spring.cn.config.autowire.AddressBean"
        p:city="成都" p:street="天府大道"/>

    <!--手动装配-->
    <!--<config id="personBean" class="com.spring.cn.configig.autowire.PersonBean"-->
        <!--p:name="liangd" p:carBean-ref="carBean" p:addressBean-ref="addressBean"/>-->
    <!--
        1、使用autewire属性指定自动装配方式
        2、byName 通过当前bean的类名和当前bean的setter构造风格(id名)进行自动装配
            若有匹配的,则进行自动装配,若没有匹配的,则不装配(例如id名字与类名不一致)
        3、通过byType自动装配bean,不允许IOC容器中有两个相同类型的bean,否则抛异常
    -->
    <!--自动装配-->
    <bean id="personBean" class="com.spring.cn.config.autowire.PersonBean"
        p:name="liangd" autowire="byName"/>

    <!--<config id="personBean" class="com.spring.cn.configig.autowire.PersonBean"-->
        <!--p:name="liangd" autowire="byType"/>-->
    <!--
        自动装配的缺点:
        1、在bean的配置文件里面使用autowire属性将会自动装配bean的所有属性,然而对于只自动装配个别字段,显得不够灵活
        2、autowire属性要么根据类型装配,要么根据名字装配,二者不能同时使用
        3、一般情况下,实际的项目中很少使用自动装配功能。但在使用一些框架的时候用autowire更方便
    -->
</beans>

 

posted @ 2020-12-01 16:46  donleo123  阅读(112)  评论(0编辑  收藏  举报