入门一:依赖注入

前言:前几天看一篇文章,大意是说应该为自己写一本书,通过写书,你会对某一问题理解的更全面,更透彻。想了几天,决定把自己学习spring的过程记录下来,看似简单的几行代码,写成一篇文章,还真费了不少时间。以前学习的时候对照着书敲代码输出结果就感觉OK,写这篇文章的时候整体的轮廓逐渐清晰,有了全面的认识,书中许多页说明的内容精炼为几句话。

1环境准备

1.1下载springspring-framework-3.2.2.RELEASE-dist

解压到路径:spring-framework-3.2.2.RELEASE

1.2新建JAVA项目

1.3导入相关JAR

1.3.1spring

spring-core-3.2.2.RELEASE.jar

spring-beans-3.2.2.RELEASE.jar

1.3.2log包,spring的日志使用了log4j,需要导入相关包。

log4j-1.2.8.jar.jar

commons-logging-1.0.4.jar

commons-logging-api-1.1.jar

2一个项目

说明:SPING的第一个功能,IOC(控制反转)DI(依赖注入)

MartinFowler2004年的一篇论文中提到:控制的什么方面被反转了?他总结说是获得依赖对象的方式反转了。有点抽象,先看代码再理解。

2.1需求:向控制台输出:某人说:你好,spring!

2.2相关程序

2.2.1接口:IHello.java

2.2.2实现类:CHello.java

2.3.3spring配置文件:hello.xml

2.3.4应用类:HelloAppSpring.java

3实现代码

3.1接口:IHello.java

packagecuigh.spring.ioc.hello;

/*

*功能:定义一个接口,与实现分离,业务逻辑在接口中定义,在实现类中实现。

**/

publicinterfaceIHello{

/*

*功能:某人说:你好,spring!

*参数:某人

*返回:无

**/

publicvoidsayHello(Stringname);

}

3.2实现类:CHello.java

packagecuigh.spring.ioc.hello;

/*

*功能:实现接口IHello功能

**/

publicclassCHelloimplementsIHello{

/*

*功能:向控制台输出一句话,某人说:你好,spring!

*参数:某人

*返回:无

**/

@Override

publicvoidsayHello(Stringname){

System.out.println(name+"说:你好,spring!");

}

}

3.3spring配置文件:hello.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<beansxmlns="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">

<!--说明:

1实现类定义

2容易出错的地方为拼写错误,建议采用复制、粘贴,避免不必要的错误

-->

<beanid="hello"

class="cuigh.spring.ioc.hello.CHello">

</bean>

</beans>

3.4应用类:HelloAppSpring.java

packagecuigh.spring.ioc.hello;

importorg.springframework.beans.factory.beanfactory;

importorg.springframework.beans.factory.xml.Xmlbeanfactory;

importorg.springframework.core.io.FileSystemResource;

importorg.springframework.core.io.Resource;

@SuppressWarnings("deprecation")

publicclassHelloAppSpring{

publicstaticvoidmain(String[]args)throwsException{

//使用步骤:1构造一个Resource对象,参数为配置文件,本例中为:hello.xml

StringfileName=System.getProperty("user.dir")+"\\bin\\cuigh\\spring\\ioc\\hello\\"

+"hello.xml";

Resourceresource=newFileSystemResource(fileName);

//使用步骤:2获得beanfactory

beanfactoryfactory=newXmlbeanfactory(resource);

//使用步骤:3通过beanfactory获得实现类的实例,本例中为cuigh.spring.ioc.hello.CHello

//相当于:IHellohello=newcuigh.spring.ioc.hello.CHello();

IHellohello=(IHello)factory.getBean("hello");

//用步骤:4调用业务方法,本例中为sayHello("张三")

hello.sayHello("张三");

}

}

总结:

HelloAppSpring.java中依赖的类cuigh.spring.ioc.hello.CHello通过

SPRING注入。

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...