控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,能够用来减低计算机代码之间的耦合度。其中最多见的方式叫作依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)java
在平常程序开发过程中,咱们推荐面向抽象编程,面向抽象编程会产生类的依赖,固然若是你够强大能够本身写一个管理的容器,可是既然spring以及实现了,而且spring如此优秀,咱们仅仅须要学习spring框架即可。 当咱们有了一个管理对象的容器以后,类的产生过程也交给了容器,至于咱们本身的app则能够不须要去关系这些对象的产生了。git
为何要把类生产的过程交给容器:有利于作一些通用的代码抽离,能够类比一下 代理设计模式github
虽然下面即将说到3种配置方式,但原理上,SpringIOC只有2中注入方法:基于setter注入、基于构造器注入。而所谓的3种配置方式(编程风格)只是不一样的配置手段罢了。spring
This is indexService function.
This is injectedString: 445566ddeeff
This is index dao
复制代码
<bean id="indexService" class="cn.zephyr.IndexServiceImpl" >
<constructor-arg name="indexDao" ref="indexDao"/>
<constructor-arg name="injectedString" value="112233aabbcc"/>
</bean>
<bean id="indexDao" class="cn.zephyr.IndexDao"/>
复制代码
IndexServiceImpl
添加全参、无参构造器的lombok注解@Data
@AllArgsConstructor
@NoArgsConstructor
public class IndexServiceImpl implements IndexService {
...
}
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">
...
</beans>
</xml>
复制代码
<bean id="indexService" class="cn.zephyr.IndexServiceImpl" p:indexDao-ref="indexDao" p:injectedString="445566ddeeff"/>
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd ">
...
</beans>
</xml>
复制代码
<bean id="indexService" class="cn.zephyr.IndexServiceImpl" c:indexDao-ref="indexDao" c:injectedString="445566ddeeff">/>
复制代码
基于注解的方式能够说是极大的减轻了配置工做,使得咱们可以更加专一于业务代码编写:编程
基于java config的方式,我的以为让咱们从繁琐的xml配置解放出来,使用java config能够提升代码可读性,减小出错: 主要业务代码以下(再也不使用spring.xml,使用SpringConfig.java
取代),执行后能够看到一样的效果:
设计模式