Spring支持3种依赖注入方式,分别为属性注入、构造器注入和工厂方法注入(很少使用,不推荐),下面分别对属性注入和构造器注入详细讲解。
1、常量注入
属性注入是通过setter方法注入Bean的属性值,属性注入使用<property>元素,使用name属性指定Bean的属性名称,使用value属性或者<value>子节点指定属性值。
beans.xml文件主要内容
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); }}
运行结果截图如下:
以上就是属性注入的例子
2、构造器注入
2.1 按照索引匹配
beans.xml
结果:
2.2 按类型匹配
beans.xml
12 3 4 5 6
结果: