`

二 开启spring之旅

 
阅读更多
1 首先下载spring 

最佳答案 版本2.5.6,官网下载,最新版本是3.0.0.M3,不过还不成熟,不适合学习,你用2.5.6就好了
这是下载页面:
http://www.springsource.com/download/community?project=Spring%20Framework

下面这是下载链接:
http://s3.amazonaws.com/dist.springframework.org/release/SPR/spring-framework-2.5.6-with-dependencies.zip
这个是最全的,spring所有依赖关系都在里面,要70多M

http://s3.amazonaws.com/dist.springframework.org/release/SPR/spring-framework-2.5.6-with-docs.zip
这是个spring+它的文档的,要35M左右


2 首先使用到的jar
dist\spring.jar
lib\jakarta-commons\commons-logging.jar
如果使用了切面编程(AOP),还需要下列jar文件
lib/aspectj/aspectjweaver.jar和aspectjrt.jar
lib/cglib/cglib-nodep-2.1_3.jar
如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件
lib\j2ee\common-annotations.jar



3 实例化spring容器

实例化Spring容器常用的两种方式:

方法一:
在类路径下寻找配置文件来实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"beans.xml"});

方法二:
在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[]{“d:\\beans.xml“});

Spring的配置文件可以指定多个,可以通过String数组传入。


4 从spring容器中得到bean
当spring容器启动后,因为spring容器可以管理bean对象的创建,销毁等生命周期,
所以我们只需从容器直接获取Bean对象就行,而不用编写一句代码来创建bean对象。从容器获取bean对象的代码如下:

ApplicationContext ctx = new ClassPathXmlApplicationContext(“beans.xml”);
OrderService service = (OrderService)ctx.getBean("personService");

1 建一个接口
package cn.itcast.service;

public interface PersonService {

	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#save()
	 */
	public void save();

}

2 接一个接口的实现类
package cn.itcast.service.impl;

import cn.itcast.service.PersonService;



public class PersonServiceBean implements PersonService {

	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#save()
	 */
	/* (non-Javadoc)
	 * @see cn.itcast.service.impl.PersonService#save()
	 */
	public void save(){
		System.out.println("我是save()方法");
	}
}

3 配置
<bean id="personservice" class="cn.itcast.service.impl.PersonServiceBean"></bean>

4 调用

ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
PersonService personService = (PersonService)ctx.getBean("personservice");
personService.save();

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics