通过使用构造器来配置Bean

1、创建Car类,Car.java

package spring.beans;

public class Car {

    private String brand;
    private String corp;
    private int price;
    private double maxSpeed;
    //创建构造器
    public Car(String brand,String corp,double maxSpeed){
        super();
        this.brand=brand;
        this.corp=corp;
        this.maxSpeed=maxSpeed;
    }

    @Override
    public String toString() {
        return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price + ", maxSpeed=" + maxSpeed + "]";
    }

}

注意上面的toString()方法是按如下方式自动生成的:
这里写图片描述

2、创建applicationContext配置文件:

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

    <!-- 通过 构造方法来配置bean的属性-->
    <!-- 使用构造器注入属性值可以指定参数的位置和参数的类型,以区分重载的构造器 -->
    <bean id="car" class="spring.beans.Car">
        <constructor-arg value="Audi" index="0"></constructor-arg>
        <constructor-arg value="NanJing" index="1"></constructor-arg>
        <constructor-arg value="120" type="double"></constructor-arg>
    </bean>


</beans>

3、创建主函数Main.java

package spring.beans;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        Car car=ctx.getBean(Car.class);
        System.out.println(car);
    }
}

4、执行Main.java,效果如下:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值