博客
关于我
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 我们必须知道的那些事
查看>>
Nginx 源码完全注释(11)ngx_spinlock
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的 SSL 模块安装
查看>>
Nginx 的优化思路,并解析网站防盗链
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
nginx 禁止以ip形式访问服务器
查看>>
Nginx 结合 consul 实现动态负载均衡
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置服务器文件上传与下载
查看>>
Nginx 配置清单(一篇够用)
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
Nginx 集成Zipkin服务链路追踪
查看>>
nginx 集群配置方式 静态文件处理
查看>>
nginx+php的搭建
查看>>
nginx+tomcat+memcached
查看>>