依赖注入(DI)和控制反转(IOC)的详细讲解 spring容器(spring注解
在看此片文章之前,请先看下面一片,是最基础的依赖注入和控制反转的spring简单实现。简单到看完就可以基本理解。 依赖注入(Dependency Injection)和控制反转(Inversion of Control)是同一个概念。 不管是依赖注入,还是控制反转,都说明Spring采用动态、灵活的方式来管理各种对象。对象与对象之间的具体实现互 (哎,POJO知道是啥吗?不知道的话,看链接,如下:POJO是什么,怎么理解,大师兄查了,看看吧。点我。) 1,两个接口的声明。 person接口 /** * 定义Person接口 * <p> * Created by lxk on 2017/3/22 */ interface Person { void useAxe(); //Person接口里定义一个使用斧子的方法 }斧子接口 /** * 定义Axe(斧子英文Axe)接口 * <p> * Created by lxk on 2017/3/22 */ interface Axe { String chop(); //Axe接口里有个砍(chop)的方法,返回String类型 } 2,两个实现类。 第一类斧子 import org.springframework.stereotype.Component; /** * Axe的第二个实现类 SteelAxe 钢斧 * 这个@Component 等价于 <bean id="steelAxe" class="..SteelAxe"> * Created by lxk on 2017/3/22 */ @Component class SteelAxe implements Axe{ /** 实现Axe接口的chop方法 */ @Override public String chop() { return "钢斧砍柴真快"; } }第二类斧子 import org.springframework.stereotype.Component; /** * Axe的第一个实现类 StoneAxe 石斧 * 这个@Component("stoneAxe") 等价于 <bean id="stoneAxe" class="..StoneAxe"> * Created by lxk on 2017/3/22 */ @Component("stoneAxe") class StoneAxe implements Axe { /** 实现Axe接口的chop方法 */ @Override public String chop() { return "石斧砍柴好慢"; } }人,使用斧子的实体。 import javax.annotation.Resource; /** * Person的实现类(Chinese实现Person接口) * * Created by lxk on 2017/3/22 */ @Component("chinese") class Chinese implements Person { /** 面向Axe(斧子)接口编程,而不是具体的实现类 */ @Resource(name = "stoneAxe") private Axe axe; /** 实现Person接口的useAxe方法 */ public void useAxe() { System.out.println(axe.chop()); } } 3,主方法测试类。 import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * 依赖注入,使用注解实现 * <p> * Created by lxk on 2017/3/22 */ public class Main { public static void main(String[] args) { //因为是独立的应用程序,显式地实例化Spring的上下文。下面是启动spring容器代码:寻找配置文件实例化容器 ApplicationContext context = new ClassPathXmlApplicationContext("com/lxk/spring/ioc/applicationContext.xml"); //通过Person bean的id来获取bean实例,面向接口编程,因此 //此处强制类型转换为接口类型 Person p = (Person) context.getBean("chinese"); //直接执行Person的userAxe()方法。 p.useAxe(); } } 4,对应的配置文件,spring项目必须的。 <?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.lxk.spring.ioc"/> </beans> 5,执行结果:
6,文件结构如下:
7,说明: 首先你要知道,在spring容器启动之后,会根据你的配置文件里面 最后,觉得写的好的,对你有帮助的,不嫌弃麻烦的,点个赞,觉得不好的,提出来我改之,懒得提也可以,但是,麻烦,放下脚,不要踩我文章。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |