首页 > 学院 > 开发设计 > 正文

3、spring的五种自动装配方式

2019-11-08 03:06:00
字体:
来源:转载
供稿:网友

sPRing的五种自动装配方式

no —— 默认情况,自动装配方式为手动装配,即通过ref手动设定byName —— 根据属性名称自动装配,如果一个bean的名称和其他bean属性一致,则进行自动装配byType——按照数据类型进行自动装配,如果一个bean的名称和其他bean的属性的数据类型一致,则进行兼容并自动装配constructor ——通过构造函数参数的byType方式。autodetect —— 如果找到默认的构造函数,使用“自动装配用构造”; 否则,使用“按类型自动装配”。

在演示五种装配方式时,需要构建两个辅助类

Customer.java

public class Customer { private Address address; public Customer(Address address){ this.address = address; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; }}

Address.java

public class Address { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }}

1、no 默认装配方式

<!-- 默认自动装配方式为no时,手动装配bean --> <bean id="customer" class="com.main.autowrite.defaul.Customer"> <property name="address" ref="address"></property> </bean> <bean id="address" class="com.main.autowrite.defaul.Address"></bean>

2、byName 方式自动装配

<!-- byName自动装配方式 --> <bean id="customer" class="com.main.autowrite.byname.Customer" autowire="byName"> </bean> <bean id="address" class="com.main.autowrite.byname.Address"> <property name="address" value="Block A 888, CA" /> </bean>

3、byType方式自动装配

<!-- byType自动装配方式 --> <bean id="customer" class="com.main.autowrite.bytype.Customer" autowire="byType"> </bean> <bean id="address" class="com.main.autowrite.bytype.Address"> <property name="address" value="Block A 888, CA" /></bean>

4、constructor方式自动装配

<!-- constructor自动装配方式 --> <bean id="customer" class="com.main.autowrite.constructor.Customer" autowire="constructor"> </bean> <bean id="address" class="com.main.autowrite.constructor.Address"> <property name="address" value="Block A 888, CA" /></bean>

5、autodetect方式自动装配

说明:auto-wire’ 和 ‘dependency-check’ 相结合,以确保属性始终自动装配成功。

<!-- autodetect自动装配方式 --> <bean id="customer" class="com.main.autowrite.autodetect.Customer" autowire="autodetect"> </bean> <bean id="address" class="com.main.autowrite.autodetect.Address"> <property name="address" value="Block A 888, CA" /></bean>

测试方法: 说明:以上五种装配方式均可用以下方式来进行验证,套路是一样的 这里用byName方式来演示

@Test public void test(){ applicationContext context = new ClassPathxmlApplicationContext("com/main/autowrite/byname/custom.xml"); Customer customer = (Customer)context.getBean("customer"); System.out.println(customer.getAddress().getAddress()); }

运行结果为: 这里写图片描述


上一篇:maven引入本地jar包

下一篇:三位 水仙花

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表