码迷,mamicode.com
首页 > 其他好文 > 详细

七.自动装配

时间:2020-09-12 21:16:05      阅读:30      评论:0      收藏:0      [点我收藏+]

标签:dog   com   http   name   lock   end   存在   encoding   自动   

1.测试自动装配

一个人有2个宠物:人的类里面有2个宠物的类引用

1.1 byName自动装配

   <!--    byname:就是在xml中找和我们set后面一样的bean的id/name 一样就给装上 -->
    <!--     如上面的cat spring就自动找到他 将他装上了 改为cats就找不到了-->
    <!--只能取小写的 大写的id找不到    -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dog" class="com.why.TestAuto_Assembling.Dog"/>
    <bean name="cat" class="com.why.TestAuto_Assembling.Cat"/>
    <bean name="human" class="com.why.TestAuto_Assembling.Human" autowire="byName"/>
</beans>

1.2 byType

byType:自动在上下文寻找和我们属性类型一样的bean并装填 但是这个bean只能有

一个 如果存在多个 报错 但是可以省略id了

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="dog" class="com.why.TestAuto_Assembling.Dog"/>
    <bean name="cat" class="com.why.TestAuto_Assembling.Cat"/>
    <bean name="human1" class="com.why.TestAuto_Assembling.Human" autowire="byType"/>
</beans>

2.总结

  • byName 保证id唯一 且id和set方法后的属性名一致!!!

  • byType 保证容器里只有一个bean 且类型一样!!!

七.自动装配

标签:dog   com   http   name   lock   end   存在   encoding   自动   

原文地址:https://www.cnblogs.com/whydbk/p/13589380.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!