博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 依赖注入
阅读量:4049 次
发布时间:2019-05-25

本文共 1886 字,大约阅读时间需要 6 分钟。

– Start


对象都不是孤立存在的,它们之间有依赖关系,以此来协同工作,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,更简洁。

基于 Setter 方法的依赖注入

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

你可能感兴趣的文章
JavaScript的一些基础-数据类型
查看>>
JavaScript基础知识(2)
查看>>
转载一个webview开车指南以及实际项目中的使用
查看>>
android中对于非属性动画的整理
查看>>
一个简单的TabLayout的使用
查看>>
ReactNative使用Redux例子
查看>>
Promise的基本使用
查看>>
coursesa课程 Python 3 programming 统计文件有多少单词
查看>>
coursesa课程 Python 3 programming 输出每一行句子的第三个单词
查看>>
Returning a value from a function
查看>>
coursesa课程 Python 3 programming Functions can call other functions 函数调用另一个函数
查看>>
coursesa课程 Python 3 programming The while Statement
查看>>
course_2_assessment_6
查看>>
coursesa课程 Python 3 programming course_2_assessment_7 多参数函数练习题
查看>>
coursesa课程 Python 3 programming course_2_assessment_8 sorted练习题
查看>>
在unity中建立最小的shader(Minimal Shader)
查看>>
1.3 Debugging of Shaders (调试着色器)
查看>>
关于phpcms中模块_tag.class.php中的pc_tag()方法的含义
查看>>
vsftp 配置具有匿名登录也有系统用户登录,系统用户有管理权限,匿名只有下载权限。
查看>>
linux安装usb wifi接收器
查看>>