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>
就要用上述来进行注入