博客
关于我
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());    }}
四 测试结果
顺平 养 小黄
你可能感兴趣的文章
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>
Nginx+Tomcat实现动静分离
查看>>
nginx+Tomcat性能监控
查看>>
nginx+uwsgi+django
查看>>
nginx+vsftp搭建图片服务器
查看>>
Nginx-http-flv-module流媒体服务器搭建+模拟推流+flv.js在前端html和Vue中播放HTTP-FLV视频流
查看>>
nginx-vts + prometheus 监控nginx
查看>>
nginx: [emerg] getpwnam(“www”) failed 错误处理方法
查看>>
nginx:Error ./configure: error: the HTTP rewrite module requires the PCRE library
查看>>
Nginx、HAProxy、LVS
查看>>
Nginx下配置codeigniter框架方法
查看>>
Nginx中使用expires指令实现配置浏览器缓存
查看>>
Nginx之二:nginx.conf简单配置(参数详解)
查看>>
Nginx代理websocket配置(解决websocket异常断开连接tcp连接不断问题)
查看>>
Nginx代理初探
查看>>
nginx代理地图服务--离线部署地图服务(地图数据篇.4)
查看>>
Nginx代理外网映射
查看>>
Nginx代理模式下 log-format 获取客户端真实IP
查看>>
Nginx代理解决跨域问题(导致图片只能预览不能下载)
查看>>