Spring注入方式(1)

时间:2023-12-29 21:34:20

Spring支持3种依赖注入方式,分别为属性注入、构造器注入和工厂方法注入(很少使用,不推荐),下面分别对属性注入和构造器注入详细讲解。

1、常量注入

  属性注入是通过setter方法注入Bean的属性值,属性注入使用<property>元素,使用name属性指定Bean的属性名称,使用value属性或者<value>子节点指定属性值。

beans.xml文件主要内容

<!--通过属性注入方式配置  -->
<bean id="person" class="com.spring.Person">
<property name="name" value="Tom"></property>
<property name="age" value="29"></property>
</bean>

Person.java

package com.spring;
public class Person {
private String name;
private int age;
private double height;
private double weight; public Person(String name, int age, double height, double weight) {
super();
this.name = name;
this.age = age;
this.height = height;
this.weight = weight;
} public Person() {
super();
} public double getHeight() {
return height;
} public void setHeight(double height) {
this.height = height;
} public double getWeight() {
return weight;
} public void setWeight(double weight) {
this.weight = weight;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", height=" + height + ", weight=" + weight + "]";
} }

Main.java

package com.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
Person person = (Person) ctx.getBean("person");
System.out.println(person);
}
}

运行结果截图如下:

Spring注入方式(1)

以上就是属性注入的例子

2、构造器注入

2.1 按照索引匹配

beans.xml

<bean id="person1" class="com.spring.Person">
<constructor-arg value="Tim" index="0"></constructor-arg>
<constructor-arg value="30" index="1"></constructor-arg>
<constructor-arg value="30" index="3"></constructor-arg>
<constructor-arg value="65" index="2"></constructor-arg> </bean>

结果:

Spring注入方式(1)

2.2 按类型匹配

beans.xml

 <bean id="person2" class="com.spring.Person">
<constructor-arg value="34" type="int"></constructor-arg>
<constructor-arg value="175" type="double"></constructor-arg>
<constructor-arg value="Jerry" type="java.lang.String" ></constructor-arg>
<constructor-arg value="70" type="double"></constructor-arg>
</bean>

结果:

Spring注入方式(1)