感谢ITCAST发布的免费视频。
spring version:2.5.6
Spring需要的jar
到http://www.springsource.org/download下载spring,然后进行解压缩,在解压缩目录中找到下面的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
配置文件模版:
<?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.5.xsd">
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<bean id="..." class="...">
<!-- collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions go here -->
</beans>
该模版可以从spring的参考手册中得到。配置文件的取名可以任意,文件可以存放在任何目录下,但考虑到通用性,一般放在类路径下。
实例化spring容器
两种方式:
方法一:
在类路径下寻找配置文件来实例化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{“beans.xml”});
方法二:
在文件系统路径下寻找配置文件来实例化容器
ApplicationContext ctx = new FileSystemXmlApplicationContext(new String[] {“d:\\beans.xml”});
Spring的配置文件可以指定多个,可以通过String数组传入
Bean有id和name属性,id不能包含特殊字符,如果需要使用特殊字符,那么就需要使用name,一般使用id即可