Spring 依赖注入的方式(四)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaizuidebanli/article/details/83099826

一、Spring 依赖注入的方式

这里是引用

二、属性注入方式

这里是引用

<!-- 配置一个 bean -->
<bean id="helloWorld" class="atguigu.Spring.HelloWorld">
	<!-- 为属性赋值 -->
	<!-- 通过属性注入: 通过 setter 方法注入属性值 -->
	<property name="user" value="Tom"></property>
</bean>

三、构造方法注入

这里是引用

  1. Bean类,只提供构造方法,不提供set方法
/**
只提供构造方法,不提供set方法
*/
public class Car {

	private String company;
	private String brand;

	private int maxSpeed;
	private float price;

	public Car(String company, String brand, float price) {
		super();
		this.company = company;
		this.brand = brand;
		this.price = price;
	}

	public Car(String company, String brand, int maxSpeed) {
		super();
		this.company = company;
		this.brand = brand;
		this.maxSpeed = maxSpeed;
	}

	public Car(String company, String brand, int maxSpeed, float price) {
		super();
		this.company = company;
		this.brand = brand;
		this.maxSpeed = maxSpeed;
		this.price = price;
	}

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

  1. xml配置
<!-- 通过构造器注入属性值 , 默认按照参数定义顺序来注入,棵通过index精确定位-->
<!-- 若一个 bean 有多个构造器, 如何通过构造器来为 bean 的属性赋值 -->
<!-- 可以根据 index 和 value 进行更加精确的定位. (了解) -->
<bean id="car" class="com.atguigu.spring.helloworld.Car">
	<constructor-arg value="KUGA" index="1"></constructor-arg>
	<constructor-arg value="ChangAnFord" index="0"></constructor-arg>
	<constructor-arg value="250000" type="float"></constructor-arg>
</bean>
  1. 对于重载的构造方法,我们如何正确注入呢?(位置,索引解决不了,此时我们可以使用类型区分)
<!-- 若一个 bean 有多个构造器, 如何通过构造器来为 bean 的属性赋值 -->
<!-- 可以根据 index 和 value 进行更加精确的定位. (了解) -->
<bean id="car" class="com.atguigu.spring.helloworld.Car">
	<constructor-arg value="KUGA" index="1"></constructor-arg>
	<constructor-arg value="ChangAnFord" index="0"></constructor-arg>
	<constructor-arg value="250000" type="float"></constructor-arg>
</bean>

<bean id="car2" class="com.atguigu.spring.helloworld.Car">
	<constructor-arg value="ChangAnMazda"></constructor-arg>
	<constructor-arg value="Audi" index="1"></constructor-arg>
	<constructor-arg value="180" type="int"></constructor-arg>
</bean></bean>

猜你喜欢

转载自blog.csdn.net/kaizuidebanli/article/details/83099826