1. 建立maven项目
2. 导入spring支持
<repositories>
<repository>
<id>springsource-repo</id>
<name>SpringSource Repository</name>
<url>http://repo.springsource.org/release</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.1.RELEASE</version>
</dependency>
</dependencies>
这个spring网站有详细说明 http://www.springsource.org/spring-framework
3. 创建spring 容器配置文件
参见:spring-framework-reference.pdf 4.2
spring容器配置文件可以是一个或者多个xml,名字自己取,,建议存放到src/main/resource下面,比如这里建立ApplicationContext.xml
<?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-3.0.xsd">
<bean init-method="showTest" id="AutoLoadBean" class="com.talkweb.test.bean.impl.AutoLoadBeanImpl">
</bean>
<!-- more bean definitions go here -->
</beans>
在里面配置bean,bean需要在外部创建一个interface,一个实现类
写一个测试类来加载容器:
public class TestWebContext {
ApplicationContext context;
@Before
public void loadSpringContext(){
context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
}
@Test
public void test() {
// AutoLoadBean autoLoadBean = (AutoLoadBean)context.getBean("AutoLoadBean");
// Assert.assertNotNull( autoLoadBean );
// autoLoadBean.showTest();
}
}
4. 在web项目中,加载spring容器
参考: Convenient ApplicationContext instantiation for web applications spring-framework-reference 4.14
在web.xml里面配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
也可以配置自动加载的servlet
<!-- or use the ContextLoaderServlet instead of the above listener
<servlet>
<servlet-name>context</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
-->
在maven工程结构,spring的xml放到了src/main/resource下面,这里的引用路径需要这样配置:
classpath*:ApplicationContext.xml
这种格式称为Ant-style,参考我的另外一个文章 spring Ant-styles