本文共 1886 字,大约阅读时间需要 6 分钟。
对象都不是孤立存在的,它们之间有依赖关系,以此来协同工作,Spring 支持基于构造方法和 setter 方法两种依赖注入方式。
基于构造器的依赖注入非常简单,下面是一个简单的例子。注意 Spring 通过类型匹配参数,如果构造器有多个类型相同的参数,我们可以通过 index 指定参数序号。
package shangbo.spring.core.example19;public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String toString() { return "[name=" + name + ", age=" + age + "]"; }}
package shangbo.spring.core.example19;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App { public static void main(String[] args) { // 实例化 Spring IoC 容器 ApplicationContext context = new ClassPathXmlApplicationContext("example.xml", Person.class); // 从容器中获得 Person 对象 Person p = context.getBean(Person.class); // 使用对象 System.out.println(p); }}
我们也可以使用 c 命名空间方式注入bean,更简洁。
package shangbo.spring.core.example20;public class Person { private String name; private int age; // // Setter // public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String toString() { return "[name=" + name + ", age=" + age + "]"; }}
package shangbo.spring.core.example20;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class App { public static void main(String[] args) { // 实例化 Spring IoC 容器 ApplicationContext context = new ClassPathXmlApplicationContext("example.xml", Person.class); // 从容器中获得 Person 对象 Person p = context.getBean(Person.class); // 使用对象 System.out.println(p); }}
我们也可以使用 p 命名空间方式注入bean,更简洁。
– 声 明:转载请注明出处 – Last Updated on 2017-06-17 – Written by ShangBo on 2017-05-22 – End