博客
关于我
spring的自动装配
阅读量:188 次
发布时间:2019-02-28

本文共 2040 字,大约阅读时间需要 6 分钟。

一 自动装配
<bean id="foo" class="...Foo" autowire="autowire type">
有四种自动装配类型:
1 byName:寻找和属性名相同的bean,若找不到,则装不上。
2 byType:寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常。
3 constructor:查找和bean的构造参数一致的一个或多个bean,若找不到或找到多个,抛异常。按照参数的类型装配。  
4 autodetect:(3)和(2)之间选一个方式。不确定性的处理,与(3)或(2)一致。
5 defualt:这个需要在<beans defualt-autorwire="指定" />
这个需要在<beans defualt-autorwire="指定" />
当你在<beans >指定了default-atuowrite后,所有的bean的默认的autowire就是指定的装配方法。
如果没有在<beans defualt-autorwire="指定" />,没有defualt-autorwire="指定",则默认是defualt-autorwire="no"。
6 no:不自动装配,这是autowrite的默认值。
二 byName原理图
三 举例
Dog
package com.hsp.autowire;import javax.annotation.Resource;public class Dog {        private String name;        private int age;        public String getName() {                return name;        }        public void setName(String name) {                this.name = name;        }        public int getAge() {                return age;        }        public void setAge(int age) {                this.age = age;        }}
Master
package com.hsp.autowire;public class Master {        private String name;        private Dog dog;        public String getName() {                return name;        }        public void setName(String name) {                this.name = name;        }        public Dog getDog() {                return dog;        }        public void setDog(Dog dog) {                this.dog = dog;        }}
beans.xml
顺平
App1
package com.hsp.autowire;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App1 {    /**     * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        ApplicationContext ac=new ClassPathXmlApplicationContext("com/hsp/autowire/beans.xml");        //获取        Master master=(Master) ac.getBean("master");        System.out.println(master.getName()+" 养 "+master.getDog().getName());    }}
四 测试结果
顺平 养 小黄
你可能感兴趣的文章
Netty:ChannelPipeline和ChannelHandler为什么会鬼混在一起?
查看>>
Netty:原理架构解析
查看>>
Network Dissection:Quantifying Interpretability of Deep Visual Representations(深层视觉表征的量化解释)
查看>>
Network Sniffer and Connection Analyzer
查看>>
Network 灰鸽宝典【目录】
查看>>
Networkx写入Shape文件
查看>>
NetworkX系列教程(11)-graph和其他数据格式转换
查看>>
Networkx读取军械调查-ITN综合传输网络?/读取GML文件
查看>>
network小学习
查看>>
Netwox网络工具使用详解
查看>>
Net与Flex入门
查看>>
net包之IPConn
查看>>
Net操作配置文件(Web.config|App.config)通用类
查看>>
Neutron系列 : Neutron OVS OpenFlow 流表 和 L2 Population(7)
查看>>
New Relic——手机应用app开发达人的福利立即就到啦!
查看>>
NFinal学习笔记 02—NFinalBuild
查看>>
NFS
查看>>
NFS Server及Client配置与挂载详解
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>