博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring的两种常见的注入
阅读量:7029 次
发布时间:2019-06-28

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

hot3.png

spring有多种依赖注入的形式,下面仅介绍spring通过xml进行IOC配置的方式:

 1, Set注入

    需要配置的bean.xml文件

Spring quick start

两个实体类  Student  , User

package org.heinrich.action;public class User {		public void read(){				System.out.println("I am reading Book of Thinking Java");	}}package org.heinrich.action;public class Student {		private User user;	public void testDi(){				user.read();	}			public void setUser(User user) {		this.user = user;	}		}

  测试SpringTest类

  package org.heinrich.action;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringTest {		public static void main(String[] args) {				ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");		Student student = (Student)ctx.getBean("student");				student.testDi();			}}

显示的结果

I am reading Book of Thinking Java

其中bean.xml还可以配置成

Spring quick start
重点:

2,   构造器注入

主要代码Student类需要给一个构造方法,参数是需要注入的类型

package org.heinrich.action;public class Student {	private User user;	public Student(User user) {		super();		this.user = user;	}	public void testDi() {		user.read();	}}

然后配置bean.xml

Spring quick start

bean.xml还有另外一个配置方式

Spring quick start

测试结果

I am reading Book of Thinking Java

转载于:https://my.oschina.net/heinrichchen/blog/599679

你可能感兴趣的文章
1.7 以函数对象取代函数
查看>>
Vue过渡效果之JS过渡
查看>>
Android项目实战(三):实现第一次进入软件的引导页
查看>>
Web Service基础——基础概念
查看>>
Linux2.4文件系统中vfsmount、安装点的dentry、设备的dentry之间的关系【转】
查看>>
POJ 1201 Intervals
查看>>
JAVA訪问URL
查看>>
APP接口基础学习一
查看>>
设计模式 策略模式 以角色游戏为背景
查看>>
【转】CSS和SVG中的剪切——clip-path属性和<clipPath>元素
查看>>
【C语言入门教程】5.4 递归
查看>>
UVALive 6915 Leveling Ground 倍增RMQ
查看>>
Inside ARC — to see the code inserted by the compiler
查看>>
云中气象 有备而来
查看>>
4.dubbo-demo+简易监控中心安装+管理控制台安装
查看>>
读书笔记《集体智慧编程》Chapter 4 : Searching and Ranking
查看>>
jquery form 插件 分类: JavaScript ...
查看>>
php二维数组访问
查看>>
用Shell实现俄罗斯方块代码(Tetris.sh)
查看>>
[zz]Ubuntu Hadoop HDFS 配置
查看>>