7、spring 依赖注入(DI)
来源:互联网 发布:飞鸟淘宝客源码下载 编辑:程序博客网 时间:2024/06/05 10:44
7、spring 依赖注入(DI)
在spring框架中,主要有以下四种依赖注入的方式
- setter方法注入
- 构造器注入
- 静态方法注入
实例工厂注入
在实际的运用中主要使用前两种,所以在本文中也主要介绍前两种DI方式
示例1:setter方法依赖注入
目录结构如下:
配置文件bean.xml:
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="HelloWorldHelprt" class="com.main.autowrite.DI.HelloWorldHelper"> <property name="helloWorldImpl" ref="helloWorldImpl" /> </bean> <bean id="helloWorldImpl" class="com.main.autowrite.DI.HelloWorldImpl"/></beans>
HelloWorld.java
package com.main.autowrite.DI;public interface HelloWorld { public void sayHello();}
HelloWorldImpl.java
package com.main.autowrite.DI;public class HelloWorldImpl implements HelloWorld{ public void sayHello() { System.out.println("Hello world"); }}
HelloWorldHelper.java
package com.main.autowrite.DI;public class HelloWorldHelper { private HelloWorldImpl helloWorldImpl; public HelloWorldHelper(){ } public void setHelloWorldImpl(HelloWorldImpl helloWorldImpl){ this.helloWorldImpl = helloWorldImpl; } public void sayHello(){ helloWorldImpl.sayHello(); }}
测试方法:
@Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext("com/main/autowrite/DI/bean.xml"); HelloWorldHelper helper = (HelloWorldHelper)context.getBean("HelloWorldHelprt"); helper.sayHello(); }
例子2:构造器方法依赖注入
在例子1的基础上
修改HelloWorldHelper类如下:
package com.main.autowrite.DI;public class HelloWorldHelper { private HelloWorldImpl helloWorldImpl; public HelloWorldHelper(HelloWorldImpl helloWorldImpl){ this.helloWorldImpl = helloWorldImpl; } public void sayHello(){ helloWorldImpl.sayHello(); }}
bean.xml
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="HelloWorldHelprt" class="com.main.autowrite.DI.HelloWorldHelper"> <constructor-arg> <ref bean="helloWorldImpl" /> </constructor-arg> </bean> <bean id="helloWorldImpl" class="com.main.autowrite.DI.HelloWorldImpl"/></beans>
测试方法和例子1的一致,无需更改
两个例子的运行结果均是下图的结果:
如需了解静态工厂以及实例工厂的依赖注入,请点击这里学习
0 0
- 7、spring 依赖注入(DI)
- spring依赖注入(DI)
- Spring 依赖注入(DI)
- spring-DI(依赖注入)
- Spring依赖注入(DI)
- Spring依赖注入(DI)
- Spring依赖注入(DI)
- Spring 依赖注入(DI)
- Spring依赖注入(DI)
- spring(依赖注入-DI)
- Spring DI 依赖注入
- Spring-DI(依赖注入)
- Spring依赖注入DI
- Spring 依赖注入(DI)
- Spring DI[依赖注入]
- Spring DI(依赖注入)
- Spring依赖注入(DI)
- Spring依赖注入DI
- Java抽象类与接口的区别
- 棋盘问题
- Java中,组合和继承的区别
- ubuntu右键添加打开终端的快捷菜单
- x210 一步步点亮LED
- 7、spring 依赖注入(DI)
- POJ 3548 Common Subsequence (LCS,dp)
- github 配置方法
- Xcode中的代码片段默认目录
- 自定义checkbox选择框的样式
- java整型类型
- PHP开发规范集成工具安装配置
- 解惑:cPanel和WHM有什么区别?
- java集合学习总结