搭建 spring maven 项目

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




  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值