博客
关于我
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());    }}
四 测试结果
顺平 养 小黄
你可能感兴趣的文章
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>