自动装配bean

spring可以把注入到IOC容器中的bean自动装配到指定的属性上。下面通过XML的方式进行自动装配需要的bean。
一、通过XML的方式进行自动装配
假设有两个类,Person和Car,现在需要把Car的bean装配到Person中的car属性上。在xml的配置中需要用到autowire属性。

类Car

package com.lzj.spring;

public class Car {

    private String brand;
    private double price;
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + ", price=" + price + "]";
    }
}

类Person

package com.lzj.spring;

public class Person {

    private String name;
    private Car car;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Car getCar() {
        return car;
    }
    public void setCar(Car car) {
        this.car = car;
    }
    @Override
    public String toString() {
        return "Person [name=" + name + ", car=" + car + "]";
    }
}

XML中的配置方式为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <bean id="car" class="com.lzj.spring.Car">
        <property name="brand" value="baoma"></property>
        <property name="price" value="100000"></property>
    </bean>

    <!--用autowire属性指定通过name进行加载。person中有一个car的属性,由于person中设置了setCar方法,指定了utowire="byName"属性后,会把IOC中的id为car的bean注入到person中的car属性上-->
    <bean id="person" class="com.lzj.spring.Person" autowire="byName">
        <property name="name" value="lzj"></property>
    </bean>

</beans>

另外:也可以指定autowire=”byType”,通过类型进行注入。由于prson中的car属性为Car类型的,spring 会在IOC中寻找是否有类型为Car的bean,如果找到了,注入到person中的car属性上。

未完。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值