Spring之構造方法注入


Talk is checp,show you the code

1.新建實體類Car,並創建兩個構造器,其實toString方法是為了測試用的,方便學習,在具體生產業務中沒誰會閑的沒事建造一個toString方法

public class Car {
    
    private String brand;
    private String corp;
    private double price;
    private int maxSpeed;
    public Car(String brand, String corp, double price) {
        this.brand = brand;
        this.corp = corp;
        this.price = price;
    }
    public Car(String brand, String corp, int maxSpeed) {
        this.brand = brand;
        this.corp = corp;
        this.maxSpeed = maxSpeed;
    }
    @Override
    public String toString() {
        return "Car [brand=" + brand + ", corp=" + corp + ", price=" + price
                + ", maxSpeed=" + maxSpeed + "]";
    }
}

2.新建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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    
    <bean id="car" class="com.auguigu.spring.beans.Car">
        <constructor-arg value="Audi" type="java.lang.String"></constructor-arg>
        <constructor-arg value="Shanghai" type="java.lang.String"></constructor-arg>
        <constructor-arg value="30000" type="int"></constructor-arg>
    </bean>
    
    <bean id="car2" class="com.auguigu.spring.beans.Car">
        <constructor-arg value="BMW" type="java.lang.String"></constructor-arg>
        <constructor-arg value="BeiJing" type="java.lang.String"></constructor-arg>
        <constructor-arg value="300.00" type="double"></constructor-arg>
    </bean>
</beans>

分別為兩個構造器注入不同的屬性值,當然是根據字段的屬性去注入的,Spring會自動匹配具有相同屬性的字段然后進行賦值

3.新建測試類Main

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 = (Car) ctx.getBean("car");
        System.out.println(car);
        car = (Car) ctx.getBean("car2");
        System.out.println(car);
    }
}

結束語

如果字面值包含特殊字符

<constructor-arg type="java.lang.String">

        <value><![CDATA[<shanghai*>]]></value>

</constructor-arg>

就要用上述來進行注入


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM