Spring依赖注入原理

Spring是一个轻型框架,这应该不是说它的功能小,而是它的功能是可选的。如下图:[img]http://dl.iteye.com/upload/picture/pic/87375/0742dd27-ce19-30c3-8903-7e8cfdefec7d.jpg[/img]
spring的core核心提供了spring框架的基本功能。包括BeanFactory,它是spring容器的基础,也是spring依赖注入的基础。
所有spring的应用上下文都是建立在核心框架上面(core)。这种模型使spring可以支持很多企业应用服务,如email、JNDI access、EJB intergration、remoting等等。
spring的依赖注入(dependency injection)在2004年之后也叫做控制反转(inversion of control)。其最大的优势是低耦合,如在下面可以简单说明依赖注入的例子:首先我们定义一个HelloWordService接口
public interface HelloWordService{
void sayHello()}

在HelloWord中实现这个接口
public class HelloWord implements HelloWordService{
private string greeting;
public HelloWord(){}
public HelloWord(String greetin){
this.greeting = greeting;
}
public void setGreeting(String greeting){
this.greeting = greeting;
}
public void sayHello(){
System.out.print(greeting);
}
}

在spring的xml配置文件中还要增加hello.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-2.0.xsd">
<bean id="helloWordService"
class="com.test.HelloWord">
<property name="greeting" value="test DI" />
</bean>
</beans>

spring的依赖注入一般有两种方法,一在构造方法中注入,二是在setter方法中注入(如本例)。[img]http://dl.iteye.com/upload/picture/pic/87385/2f58adcd-fe20-340d-8a57-b2528fdb0273.jpg[/img]
Foo类定义了Bar接口时,那Foo就并不用关心Bar的实现类,Bar的实现类可以是本地POJO、远程web服务、EJB等,而Foo类并不知道也不用关心。
BeanFactory是spring容器的基础,如使用XmlBeanFactory读取hello.xml:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class HelloApp {
public static void main(String[] args) throws Exception {
BeanFactory factory =
new XmlBeanFactory(new FileSystemResource("hello.xml"));
HelloWordService hello=
(HelloWordService) factory.getBean("helloWordService");
hello.sayHello();
}
}

然而追求低耦合也不是完美的,如低耦合的代码更难测试、重用也有困难、更难理解、特别也会出现这样的情况“解决了一个bug而带来了一个或者多个bug”。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值